我正在使用 asp.net mvc 4、EF、codefirst 与用户和角色系统建立多对多关系
用户模型:
public class User
{
#region properties
[Key]
public Int32 Id { get; set; }
[Required]
public String UserName { get; set; }
public String Password { get; set; }
[Required]
public String Email { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
public DateTime? LastLogin { get; set; }
[ForeignKey("RoleId")]
public virtual ICollection<Role> Roles { get; set; }
#endregion //properties
#region constructors
public User()
{
Roles = new HashSet<Role>();
LastUpdate = DateTime.Now;
CreationDate = DateTime.Now;
}
#endregion //constuctors
}
榜样:
public class Role
{
[Key]
public Int32 Id { get; set; }
public String Name { get; set; }
public String Description { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastUpdate { get; set; }
[ForeignKey("UserId")]
public virtual ICollection<User> Users { get; set; }
public Role()
{
Users = new HashSet<User>();
CreationDate = DateTime.Now;
LastUpdate = DateTime.Now;
}
}
上下文:
public class UserManagementContext : Context, IContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public UserManagementContext() {
Database.SetInitializer<UserManagementContext>(null);
}
void IContext.Setup(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<Role>().ToTable("Roles");
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(
m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UserRoles");
});
}
}
当生成数据库表时,表用户、角色和用户角色就在那里。然后我在用户中做一个记录,一个在角色中,一个在用户角色中以连接它们。userroles 表有两列 RoleId 和 UserId。
然后我尝试像这样加载用户的角色:
public String[] GetRoles(String userName)
{
//var user = ConcreteContext.Users.Include("Roles").Where(u => u.UserName == userName).FirstOrDefault();
var users = ConcreteContext.Users.Include(u => u.Roles);
var user = users.FirstOrDefault();
var roles = from r in user.Roles
select r.Name;
return roles.ToArray();
}
但是带有的行var users = ConcreteContext.Users.Include(u => u.Roles);
引发了下一个错误:
System.Data.SqlClient.SqlException: Invalid object name 'dbo.RoleUsers'.
如果在创建数据库时(通过使用)将 UserRoles 的 de 表名称更改为 RoleUsers m.ToTable(RoleUsers)
,我会收到很多关于错误字段名称的不同错误。
有人知道我在这里缺少什么吗?
提前致谢,
威廉