插入后在实体框架中获取记录ID [英] Get Record ID in Entity Framework after insert
本文介绍了插入后在实体框架中获取记录ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
我意识到这一定是一件相对简单的事情,但我没有得到我正在寻找的谷歌。
我需要获取我刚刚使用实体框架保存的记录的记录ID。对于SQL查询,我们使用选择@@ IDENTITY作为'身份';
如果有人可以提供帮助,我们将不胜感激。
我正在使用ASP.NET C#3.5 SP1
谢谢
Hi
I realize this must be a relatively simple thing to do, but I'm not getting what I'm looking for with Google.
I need to get the record ID of the record I just saved using the Entity Framework. With SQL queries we used "Select @@IDENTITY as 'Identity';"
If anyone can help it would be greatly appreciated.
I'm working with ASP.NET C# 3.5 SP1
Thanks
推荐答案
在您调用SaveChanges()后,EF会自动使用db生成的值填充您的业务对象。
示例:
"EF automatically populates your business objects with the db-generated values after your call to SaveChanges()."
Example:
//create a new Client object
Client c = new Client();
c.Name = "Test";
//save to db
context.AddToClients(c);
context.SaveChanges();
//EF will populate your original object with the generated values
Debug.WriteLine( " Client ID is " + c.ClientID );
实际上,EF 使用新ID填充刚刚插入的实体。我已经使用SQL提供程序为SQL Server 2008和.NET 4测试了它。
Actually, EF does populate the just inserted entity with its new ID. I have tested it using the EF provider for SQL Server 2008 and .NET 4.
这是我可以保存的代码
db.ValueDocument.add(objValueDocument );
db.SaveChanges();
然后
马上我可以通过使用以下代码获得价值
db.ValueDocument.Local [0] .ValueDocumentID;
this my code where I can save
db.ValueDocument.add(objValueDocument);
db.SaveChanges();
then
immediately i can get the value by using following code
db.ValueDocument.Local[0].ValueDocumentID;
这篇关于插入后在实体框架中获取记录ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文