Sunday, April 28, 2013

Get the Primary key on Insert Using Entity Framework


Hey guys, this is just a quick code example to show how you can get the auto incrementing Primary Key ID when inserting a new row using Entity Framework.


 
All you need to do is insert the record as you normally would, then after you saveChanges() just assign the ID to an integer as seen below.
 int TaskID;  
 using (var context = new AppName.Data.Matters.MatterContext())  
 {  
   AppName.Data.Matters.Task task = new AppName.Data.Matters.Task();  
   task.TaskCategoryID = Int32.Parse(DrpDwnTaskCategory.SelectedValue);  
   task.CreatedByUserID = UserID;  
   task.DateCreated = DateTime.Now;  
   context.Task.Add(task);  
   context.SaveChanges();  
   TaskID = task.TaskID  
 }  

How easy is that!

4 comments:

  1. WOW this is the same code that I want, I will use this surely
    thanks

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. Nice..In bulk insert scenario, this approach lowers performance.Can you kindly help?

    ReplyDelete
    Replies
    1. There are EF extensions available to help deal with the issues that arise from bulk inserts in Entity Framework, I would recommend looking onto that.

      Delete