由于我收到错误
,我遇到了正确制作导航属性的问题外键组件ID不是Administrator类型的声明属性。
我的模型基本上由一个基类User
组成,它有两个派生类Administrator
和Common
用户。我相信这是一对多的关系,因为可以有多个普通用户和管理员用户。
我的课程如下:
[Table("User")]
public class User
{
[Key]
public int ID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime RegisterDate { get; set; }
public virtual ICollection<Common> CommonUsers { get; set; }
public virtual ICollection<Administrator> Administrators { get; set;}
}
public class Administrator : Usuario
{
[ForeignKey("User")]
public int ID { get; set; }
public virtual User User { get; set; }
}
public class Common : Usuario
{
[ForeignKey("User")]
public int ID { get; set; }
public virtual User User { get; set; }
}
我在派生类中的两个ID属性上设置了foiregn键,以引用用户ID,该用户ID是表的主键。 任何意见都将不胜感激。
答案 0 :(得分:0)
语义上你的构造
public virtual ICollection<Common> CommonUsers { get; set; }
public virtual ICollection<Administrator> Administrators { get; set;}
表示单个user
可以是多个Administrators
,每个Administrator
可以分配给单个用户。
public virtual User User { get; set; }
从逻辑上讲,它应该反过来。
public class User
{
[Key]
public int ID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime RegisterDate { get; set; }
//public virtual ICollection<Common> CommonUsers { get; set; }
public virtual Administrator Administrators { get; set;}
}
public class Administrator : Usuario
{
//Primary key is required but not defined
[ForeignKey("User")]
public int ID { get; set; }
//same admin role applies to many users
public virtual ICollection<User> User { get; set; }
}
另请注意,班级名称User
可能会与System.Security.Principal.User
很可能你的意思是
public class Usuario // User
{
[Key]
public int ID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime RegisterDate { get; set; }
//public virtual ICollection<Common> CommonUsers { get; set; }
//public virtual ICollection<Administrator> Administrators { get; set;}
//define 1-to-1(0)
public virtual Common CommonUsers { get; set; }
public virtual Administrator Administrators { get; set;}
}
public class Administrator : Usuario
{
[ForeignKey("User")]
public int ID { get; set; }
public virtual User User { get; set; }
}