简体   繁体   English

EF4如何以多对多关系公开连接表

[英]EF4 How to expose the join table in a many to many relationship

Say I have the following tables: 说我有以下表格:

Essence, EssenceSet, and Essence2EssenceSet where Essence2EssenceSet holds just the IDs of the 1st 2 tables to form the M:M relationship. Essence,EssenceSet和Essence2EssenceSet,其中Essence2EssenceSet仅包含前2个表的ID以形成M:M关系。

In EF since Essence2EssenceSet has no other fields it is not exposed in the model. 在EF中,因为Essence2EssenceSet没有其他字段,所以它不会在模型中公开。 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) 我发现当我已经拥有创建记录所需的2个ID但是不一定要加载Essence和EssenceSet记录时(仅仅是它们的ID),这使得很难将记录插入到该表中

Is there a way to tell EF to not model this way and always include the join table? 有没有办法告诉EF不以这种方式建模并始终包含连接表? 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: 您可以在EF中创建M:N关系而不检索对象:

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

Anyway exposing junction table as entity is possible but you will lose comfort of EF and fallback to SQL like approach: 无论如何,将联结表暴露为实体是可能的,但是你将失去对EF的安慰并回退到SQL方法:

  1. Delete M:N relation created by designer 删除设计者创建的M:N关系
  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 为添加的关系设置参照约束

Entity Framework is an ORM, and as such, when you work with it you aren't suppose to think of the database in terms of tables but instead in terms of objects. 实体框架是一个ORM,因此,当您使用它时,您不应该根据表来考虑数据库,而是根据对象来考虑。 You shouldn't be inserting the identity into a table that holds the M2M relationship, but you should be loading one side of the relationship, which should expose a collection of the other side and add it to that collection. 您不应该将标识插入到包含M2M关系的表中,但是您应该加载关系的一侧,这应该公开另一方的集合并将其添加到该集合。 For a M2M, you may need to load the other side and do the same. 对于M2M,您可能需要加载另一侧并执行相同操作。

Also, I believe EF prefers all tables to have a single column PK (I could be wrong on this), but you may need to add a column to the M2M and designate it as a PK. 此外,我相信EF更喜欢所有表都有一个列PK(我可能错了),但您可能需要向M2M添加一列并将其指定为PK。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM