使用 linq toEntity 获取新添加记录的 ID
您好,这是我使用 linq toEntity 的第一个项目。我已经弄清楚如何创建新记录,我只需要获取分配给它的 ID,这样当我在扩展表中添加条目时,我就可以将它用作扩展表中的 FK。我允许用户创建请求,该请求可以针对多个设备,因此我有一个 Request 和 RequestedEquipment 表。以下是我用来创建请求的代码:
public void addReq(ReqType reqType, Employee reqBy, Location loc, string comm)
{
int reqID;
Request req = new Request();
req.Comments = comm;
req.Employee = reqBy;
req.ReqType = reqType;
req.RequestStatus = findReqStat(1);
req.Location = loc;
entities.AddToRequests(req);
entities.SaveChanges();
}
如何获取已创建的请求的 ID,以便我可以使用它在 RequestedEquipment 表中创建所需的条目?
Hi this is my first project using linq to entities. I've figured out how to create a new record I just need to get the ID that was assigned to it so I can use it as a FK in an extension table when I add the entries there. I'm allowing users to create request, the request can be for multiple pieces of equipment so I have a Request and RequestedEquipment table. Here is the code I'm using to create the request:
public void addReq(ReqType reqType, Employee reqBy, Location loc, string comm)
{
int reqID;
Request req = new Request();
req.Comments = comm;
req.Employee = reqBy;
req.ReqType = reqType;
req.RequestStatus = findReqStat(1);
req.Location = loc;
entities.AddToRequests(req);
entities.SaveChanges();
}
How can I get the ID of the request that was created so I can use it to Create the needed entries in the RequestedEquipment Table?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在调用 SaveChanges() 后,您应该能够从新的 Request 对象中提取 ID 值,因此类似:
SaveChanges() 应该将您的新记录保存到数据库,并且如果 ID 列设置为标识列DB,该自动生成的 ID 应通过实体框架传递回您的对象。
另外,为了以防万一,这里有一篇关于 ID 字段未自动更新问题的博客文章:
http:// dotnethacker.wordpress.com/2010/12/24/entity-framework-savechanges-doesnt-get-the- generated-identity-key/
You should be able to pull the ID value from your new Request object after the call to SaveChanges(), so something like:
SaveChanges() should save your new record to the database, and if the ID column is set as an identity column in the DB, that auto-generated ID should be passed back into your object via the entity framework.
Also just in case here's a blog post on an issue where the ID field wasn't getting updated automatically:
http://dotnethacker.wordpress.com/2010/12/24/entity-framework-savechanges-doesnt-get-the-generated-identity-key/
瑞安和迈克西托都是对的。但是,如果您需要通用解决方案,请查看以下函数:
通过这种方式,您可以创建所需的任何实体,并通过返回新创建的实体来找到其新 ID。 HTH。
Ryan and Mikecito are both right. However, if you need a generic solution take a look at the following function:
This way you can create any entity you need and by returning the newly created entity you find its new id. HTH.
我相信保存更改后,您创建的对象将填充 ID 字段。
因此,在 SaveChanges() 行之后,检查 ID 字段的值。
I believe the object you create will have the ID field populated once you save changes.
So after your SaveChanges() line, check the value of the ID field.