Is it possible to directly reference a many-to-many table using entity framework, code first

。_饼干妹妹 提交于 2019-12-01 02:33:05

No, you can't. If you want to have access to the join table via a separate entity you must replace your many-to-many relationship by two one-to-many relationships and change the navigation properties in User and Group to refer to GroupMember:

public class Group
{
    public int GroupId { get; set; }
    public virtual ICollection<GroupMember> Members { get; set; }
}

public class User
{
    public int UserId { get; set; }
    public virtual ICollection<GroupMember> Members { get; set; }
}

modelBuilder.Entity<Group>()
    .HasMany(g => g.Members)
    .WithRequired(gm => gm.Group);

modelBuilder.Entity<User>()
    .HasMany(u => u.Members)
    .WithRequired(gm => gm.User);

Why do you want this GroupMember entity? It doesn't contain any business meaning and has only references and keys. Usually you can get and modify any content of the join table by writing LINQ queries and by using the Group and User DbSets/entities and their navigation properties.

We got around this by creating a view that is only used to define the relationship. We had other fields in the lookup table that we needed to access.

The view just selects the join fields from the lookup table.

Yes you can... If you use another Context.

If you try to map more than one entity to the same table in the same Context then you will get the error. But if you put the two mappings in separate Contexts then there will be no issue. This way you can have one mapping that describes a many-many relationship with the joining table transparent as if there are only foreign keys in it... And you can have another mapping, with its own context, to expose the actual join table if you want to get at any properties of the relationship.

Yes, you can! Check this out. Also, remove GroupMembers entity and IDbSet collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!