类:
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; }
}
表:
Actions
| ID | Name |
Users
|ID | Name |
ActionUsers
| Action_ID | User_ID |
请注意,Action
和User
具有多对多关系。
假设EF可以成功映射上面的示例(我简化了原始代码),那么我决定执行以下操作:
ActionUsers
重命名为Permissions
Action
班级成员,Users
重命名为PermittedUsers
User
班级成员,Actions
重命名为Permissions
在映射Permissions
和ActionUsers
时,如何告诉EF将User.Permissions
用作关系表而不是Action.PermittedUsers
?我可以在不使用Fluent API的情况下实现所需的配置吗?
答案 0 :(得分:2)
使用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; }
}
您只需覆盖OnModelCreating
方法:
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");
});
}
如果您想拥有自己的命名约定,可以将Permission
表定义为类:
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; }
}