MVC如何设置导航属性

时间:2017-11-04 20:55:33

标签: c# asp.net entity-framework

由于我收到错误

,我遇到了正确制作导航属性的问题
  

外键组件ID不是Administrator类型的声明属性。

我的模型基本上由一个基类User组成,它有两个派生类AdministratorCommon用户。我相信这是一对多的关系,因为可以有多个普通用户和管理员用户。

我的课程如下:

    [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是表的主键。 任何意见都将不胜感激。

1 个答案:

答案 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; }
}