开发者

How can I insert and get PK Id using Entity Framework?

currently I'm Inserting like:

MyNamedEntities db = new MyNamedEntities();

My开发者_运维百科TableEntity 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 ?


If your table has defined the Id as an INT 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 new Id value:

MyTableEntity field = new MyTableEntity();
field.Name = "me";

db.MyTableEntity.AddObject(field);
db.SaveChanges();

int newID = field.Id;


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();

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜