EF4 How to expose the join table in a many to many relationship

后端 未结 2 674
天涯浪人
天涯浪人 2021-02-06 17:35

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

相关标签:
2条回答
  • 2021-02-06 18:14

    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. 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. For a M2M, you may need to load the other side and do the same.

    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.

    0 讨论(0)
  • 2021-02-06 18:16

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

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

    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
    0 讨论(0)
提交回复
热议问题