【发布时间】:2015-12-22 20:45:34
【问题描述】:
我首先学习代码并尝试为我的项目创建数据库模型。为了让我的问题简单,我将在我的模型中使用两个表 - 用户和角色
我现在的主要问题是我无法通过使用 property 获得 role。例如我的代码:
var role = dbContext.Users.FirstOrDefault(n => n.UserId== id).Role;
返回空值。我认为这是模型映射的问题。我的用户类看起来像:
public class User
{
public User()
{
Role = new Role();
}
public int UserId { get; set; }
[Required]
public string Login { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Password { get; set; }
public DateTime CreationDate { get; set; }
public DateTime LastLoginDate { get; set; }
[ForeignKey("Role")]
public int RoleId { get; set; }
public Role Role { get; set; }
public virtual ICollection<Telephone> Telephones { get; set; }
}
我的角色类:
public class Role
{
public Role()
{
Users = new List<User>();
}
public int RoleId { get; set; }
public string RoleName { get; set; }
public string RoleDescription { get; set; }
public ICollection<User> Users { get; set; }
}
这两个类的数据库上下文:
public CallCenterContext() : base(@"CONNECTIONSTRING")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
你能帮我做模型映射吗? 谢谢大家的回答!
【问题讨论】:
标签: c# .net asp.net-mvc entity-framework-5 code-first