如何使用实体框架插入和获取 PK Id?
目前我正在插入:
MyNamedEntities db = new MyNamedEntities();
MyTableEntity field = new MyTableEntity();
field.Name = "me";
db.MyTableEntity.AddObject(field);
db.SaveChanges()
但现在我想插入子元素,并且我需要 field.Id
部分
MyOtherTableEntity field = new MyOtherTableEntity();
field.TableId = new MyTableEntity.First(x => x.Id.Equals( ... ));
如何获取 field.Id
?
currently I'm Inserting like:
MyNamedEntities db = new MyNamedEntities();
MyTableEntity field = new MyTableEntity();
field.Name = "me";
db.MyTableEntity.AddObject(field);
db.SaveChanges()
But now I want to insert child elements and I need that field.Id
part
MyOtherTableEntity field = new MyOtherTableEntity();
field.TableId = new MyTableEntity.First(x => x.Id.Equals( ... ));
How can I get the field.Id
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的表已将
Id
定义为INT IDENTITY
列,那么您实际上根本不需要执行任何操作! :-)在这种情况下,只需插入您的实体,并在调用
.SaveChanges()
之后,您的对象应包含新的Id
值:If your table has defined the
Id
as anINT IDENTITY
column, then you don't really have to do anything at all! :-)In that case, just insert your entity and after the call to
.SaveChanges()
, your object should contain the newId
value:您还可以在保存更改之前或之后通过关联将它们添加到父级
像这样的东西。
地址a = 新地址();
a.city = "底特律";
字段.地址.add(a);
db.SaveChanges();
You can also just add them to the parent by the association before or after the save changes
Something like this.
address a = new address();
a.city = "Detroit";
field.address.add(a);
db.SaveChanges();