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

后端 未结 2 715
天涯浪人
天涯浪人 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: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();
       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

提交回复
热议问题