实体框架 - 添加仅与外键值连接

tst*_*ter 3 entity-framework entity-framework-4

好的,我有3个表,称之为:

  • 是PersonID
  • 名称

商店

  • STOREID
  • 名称

PersonStore

  • 是PersonID
  • STOREID

现在,我有一个表单,允许您向一个人添加商店.但是,我从表单中获取商店ID.我真的不想进行查询以从Entity Framework获取商店对象.我只想使用StoreID和Person对象添加到表中.

Ale*_*mes 5

默认情况下,在EF中,此连接表不会显示为实体,而是您将获得多对多关系,这将显示为两个导航属性

Person.Stores
Store.People
Run Code Online (Sandbox Code Playgroud)

如果要在不检索实体的情况下构建多对多关系,那么附加存根实体是最好的方法.

var person = // you already have the person
var store = new Store{StoreID = 5} // you know the storeID

ctx.AttachTo("Stores", store);
ctx.AttachTo("People", person); // assuming the person isn't already attached
person.Stores.Add(store);
ctx.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

此代码的唯一问题是,如果关系已经存在,它将失败,因此您需要确保创建关系

有关使用此类Stub实体的更多信息,请查看我的帖子.希望这可以帮助.

亚历克斯

从OP编辑:

由于我使用的是EF4,因此我使用以下代码从附加中删除字符串(感谢链接中的提示13).

var person = // you already have the person
var store = new Store{StoreID = 5} // you know the storeID

ctx.Stores.Attach(store);
person.Stores.Add(store);
ctx.SaveChanges();
Run Code Online (Sandbox Code Playgroud)