开发者

How to find an identity of the last inserted row in Entity Framework?

I am inserting data in multiple tables. I need to know the last inserted (auto-incremented) I开发者_JAVA技巧D in the table. I need to use it as a Foriegn Key in some other table.

In short I need alternative of @@Identity in T-Sql.


Entity Framework will automatically load the last inserted id to populate the primary key column of the inserted entity:

var customer = new Customer { Name = "Steven" };

context.AddObject(customer);

context.SaveChanges();

var id = customer.Id;

Note that the Id property only gets populated after calling SaveChanges() in case the StoreGeneratedPattern attribute is set to "Identity" or "Computed" for the auto-incremented ID column in the Storage part of the model.


Anyhow if you need the the id for some any other purpose ... calling EF Insert Method for some entity automatically returns the currently inserted row id ...

var rowId=db.Insert(Entity); 


You could also use this code to see the last column of your data base.

var lastColumn = context.YourTable.OrderBy(x=>x.Id).LastOrDefault();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜