我正在使用PostGre作为我的RoleProvider。 那是我的DbContext。
public class MembershipDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<RoleUser> RoleUsers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
modelBuilder.Entity<RoleUser>().ToTable("RoleUser");
}
}
模特:
public class User
{
public virtual ICollection<Role> Roles { get; set; }
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string PasswordSalt { get; set; }
}
public class Role
{
public virtual ICollection<User> Users { get; set; }
public int RoleId { get; set; }
public string Name { get; set; }
}
public class RoleUser
{
[Key, ForeignKey("Role"), Column(Order = 0)]
public int RoleId { get; set; }
[Key, ForeignKey("User"), Column(Order = 1)]
public int UserId { get; set; }
public virtual Role Role { get; set; }
public virtual User User { get; set; }
}
问题示例:
var dbContext = new MembershipDbContext();
var users = dbContext.Users.ToList();
var roles = dbContext.Roles.ToList();
//it says: "ERROR: 42P01: relation "dbo.RoleUser1" not exist"
var rolesOfFirstUser = users[0].Roles;//not working
var usersOfFirstRole = roles[0].Users;//not working
var roleUsers = dbContext.RoleUsers.ToList();//all links works perfect
我该怎么做才能让它发挥作用? This answer fixes它,但我不知道EF在哪里创建“RoleUsers”链接表。我需要它。
P.S。抱歉英文不好。
答案 0 :(得分:0)
您实际上应该将这些集合(在两个文件上)指向RoleUser,即以下内容:
public virtual ICollection<RoleUser> RoleUsers {get;set;}