How to fetch dynamic primary key Id

Posted by Shail under ASP.NET on 10/20/2015 | Points: 10 | Views : 1535 | Status : [Member] | Replies : 2
Hi.
i want to fetch primary key id using repository after insert the record .


public void Insert(TEntity entity)
{

if (entity == null)
{
throw new ArgumentNullException("entity");
}
else
{

DbSet.Add(entity);
_dbContext.Entry(entity).State = EntityState.Added;
_dbContext.SaveChanges();
_dbContext.Entry(entity).GetDatabaseValues();



}


}




Responses

Posted by: Sheonarayan on: 10/20/2015 [Administrator] HonoraryPlatinum | Points: 25

Up
1
Down
Looks like you do not need to do anything, just after inserting say var id = entity.PrimaryKeyFieldPropertyId; and you will get the inserted record primary key into id.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Shail, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rajnilari2015 on: 10/23/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 25

Up
1
Down
Here you go

public void Insert(TEntity entity) 
{

if (entity == null)
{
throw new ArgumentNullException("entity");
}
else
{

DbSet.Add(entity);
_dbContext.Entry(entity).State = EntityState.Added;
_dbContext.SaveChanges();
_dbContext.Entry(entity).GetDatabaseValues();

//Get the Inserted ID Column Value
var insertedID = entity.ID; //(Replace ID with the actual ID column)


}
}


--
Thanks & Regards,
RNA Team

Shail, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response