Many-to-many without an inverse property

霸气de小男生 提交于 2019-12-10 10:53:53

问题


I want to create a many-to-many relationship in EF. Normally I would use the InverseProperty attribute, however, in this case:

Role ( Id, Name, ICollection<Privilege> )
Privilege ( Id, Name )

I don't have an inverse property. How to tell EF that a privilege may be used in more than one Role?

[ Currently EF puts a Role_Id column in the Privilege table. This is not what I want :-) ]

Edit: I do not want to use the Fluent API, I'm looking for an attribute.


回答1:


modelBuilder.Entity<Role>()
    .HasMany(r => r.Privileges)
    .WithMany() // <- no parameter = no inverse property
    .Map(m =>
    {
        m.ToTable("RolePrivileges");
        m.MapLeftKey("RoleId");
        m.MapRightKey("PrivilegeId");
    });

I have seen that you don't want Fluent API, but it is not possible with data annotations. Mapping options with annotations are only a subset of the options with Fluent API and this is a case where a mapping option with data annotations is missing. You need Fluent API here.



来源:https://stackoverflow.com/questions/16121083/many-to-many-without-an-inverse-property

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