EF4如何公开的连接表中多对多的关系 [英] EF4 How to expose the join table in a many to many relationship

查看:154
本文介绍了EF4如何公开的连接表中多对多的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下表格:

精华,EssenceSet和Essence2EssenceSet那里Essence2EssenceSet持有1 2表只是ID来形成对M:M的关系。

Essence, EssenceSet, and Essence2EssenceSet where Essence2EssenceSet holds just the IDs of the 1st 2 tables to form the M:M relationship.

在EF因为Essence2EssenceSet有它没有在模型中没有接触其他领域。我觉得这使得它很难将记录插入此表时,我已经创造了纪录所需的2的ID,但不一定具有本质和EssenceSet记录加载(只是它们的ID)

In EF since Essence2EssenceSet has no other fields it is not exposed in the model. I find this makes it difficult to insert records into this table when I already have the 2 IDs needed to create the record but don't necessarily have the Essence and EssenceSet records loaded (Just their IDs)

有没有办法告诉EF以这种方式并不建模和总是包括联接表? ?而不检索氮与在EF:还是我失去了一个简单的方法来创建这些连接表记录

Is there a way to tell EF to not model this way and always include the join table? Or am I missing an easier way to create these join table records?

推荐答案

您可以创建中号对象以及:用

You can create M:N relation in EF without retrieving objects as well:

using (var context = new MyContext())
{
   var firstEntity = new FirstEntity { Id = firstId };
   var secondEntity = new SecondEntity { Id = secondId; }

   context.FirstEntities.Attach(firstEntity);
   context.SecondEntities.Attach(secondEntity);

   firstEntity.SecondEntities = new HashSet<SecondEntity>();
   firstEntity.SecondEntities.Add(secondEntity);

   context.SaveChanges();
}



反正露出结表作为实体是可能的,但你会失去EF的舒适性和后退到SQL类似的做法:

Anyway exposing junction table as entity is possible but you will lose comfort of EF and fallback to SQL like approach:


  1. 删除M:N由设计师

  2. 创建关系添加新实体

  3. 两列添加到代表外键

  4. 新实体映射新的实体结表

  5. 加入协会相关实体

  6. 设置引用约束为增加关系

  1. Delete M:N relation created by designer
  2. Add new entity
  3. Add two columns to the new entity representing foreign keys
  4. Map the new entity to junction table
  5. Add associations to related entities
  6. Set referential constraints for added relations

这篇关于EF4如何公开的连接表中多对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆