我正在为我的 RoleProvider 使用 PostGre。那是我的 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
我应该怎么做才能让它工作? 这个答案修复了它,但我不知道 EF 在哪里创建“RoleUsers”链接表。我需要它。
ps对不起英语不好。