Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

.net - 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) ID 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...