Reputation: 30093
Classes:
public class Action
{
public long ID{ get; set; }
public string Name{ get; set; }
public virtual ICollection<User> Users{ get; set; }
}
public class User
{
public long ID{ get; set; }
public string Name{ get; set; }
public virtual ICollection<Action> Actions{ get; set; }
}
Tables:
Actions
| ID | Name |
Users
|ID | Name |
ActionUsers
| Action_ID | User_ID |
Note that Action
and User
has many-to-many relationship.
Assuming that EF can map the above example successfully (I simplified my original code), then I decided to do the following:
ActionUsers
to Permissions
Action
class, Users
to PermittedUsers
User
class, Actions
to Permissions
How would I tell the EF to use Permissions
as relationship table instead of ActionUsers
when mapping User.Permissions
and Action.PermittedUsers
? Can I achieve the desired configuration without using Fluent API?
Upvotes: 1
Views: 658
Reputation: 10824
Using Fluent API :
public class Action
{
public long ID{ get; set; }
public string Name{ get; set; }
public virtual ICollection<User> PermittedUsers{ get; set; }
}
public class User
{
public long ID{ get; set; }
public string Name{ get; set; }
public virtual ICollection<Action> Permissions{ get; set; }
}
you can simply override OnModelCreating
method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Action>().
HasMany(c => c.PermittedUsers).
WithMany(p => p.Permissions).
Map(
m =>
{
m.MapLeftKey("Action_ID");
m.MapRightKey("User_ID");
m.ToTable("Permissions");
});
}
if you want to have your own naming convention you can define Permission
Table as a class :
public class Permissions
{
[ForeignKey("Action")]
public int Action_ID { get; set; }
public Action Action { get; set; }
[ForeignKey("User")]
public int User_ID { get; set; }
public User User { get; set; }
}
// context
public class MyContext : DbContext
{
public DbSet<Action> Actions { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Permissions> Permissions { get; set; }
}
Upvotes: 2