2

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.

D.R.
  • 20,268
  • 21
  • 102
  • 205

1 Answers1

2
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.

Slauma
  • 175,098
  • 59
  • 401
  • 420
  • Hmm, that sucks. So I have multiple points where I have defined my database structure...so is it "normal" to use FluentAPI only and do not have any attributes at all? Is CodeFirst just not used at all? – D.R. Apr 20 '13 at 14:14
  • 1
    @D.R.: Yes, for anything more than a trivial model you will usually end up with Fluent API due to the limitations of data annotations. I use it exclusively. But it's a matter of taste. You can well mix annotations (they are less verbose and faster to write) and Fluent API. – Slauma Apr 20 '13 at 14:23
  • A pity, thanks for the answer anyways. Do you know by chance if they plan to make annotations "equal" in a future update of EF? – D.R. Apr 20 '13 at 14:26
  • One more thing: Is it possible to "disable" the attribute-stuff at all? So only stuff I do with modelBuilder.Blubb() is handled? E.g. no auto-primary key if I do not specify one with modelBuilder.HasKey()? – D.R. Apr 20 '13 at 14:31
  • 1
    @D.R.: I am not aware of any plans to improve attributes to the same power than Fluent API. If you don't want any mapping by convention you would have to remove them all: http://stackoverflow.com/questions/5370518/ef-4-1-code-first-is-there-an-easy-way-to-remove-all-conventions This might change with EF 6, I believe, because it will support customizable conventions. – Slauma Apr 20 '13 at 14:56