一对一关系EF6和主键的问题

问题描述 投票:0回答:1

我有3张桌子

用户>员工>操作员

彼此之间存在一对一的关系

public class User
{
    [Key]
    public int Id { get; set; }
    public string Username { get; set; } 
    public DateTime? LoginDate { get; set; }
    public bool IsActive{ get; set; }    

    public ICollection<Role> Roles { get; set; }
    public virtual  Employee Employee { get; set; }
}

public class Employee 
{
    [Key]
    [ForeignKey("User")]
    public int Id { get; set; }
    public string Name{ get; set; }
    public string Email { get; set; }

    public int UserId { get;set; }
    public virtual User User { get; set; } 


    public virtual Operator Operator{ get; set; }  
}

public class Operator
{
    [Key]
    [ForeignKey("Employee")]
    public int Id { get; set; }

    public int EmployeeId {get;set;}
    public EmployeeEmployee{ get; set; }
}

但是,当我在Sql Server MS中创建一个图来检查关系时,这确实创建了一对一的关系。

问题是,当我只是试图从Sql直接以图形方式插入数据时,它希望我在Employee和Operator表中插入主键。为什么他们不像用户那样自动化?

c# entity-framework-6
1个回答
0
投票

首先,您不需要指定两个变量来存储相同的信息。

public int UserId { get;set; }
public int EmployeeId {get;set;}

已经存储在Id中。不需要复制它。

外键不使用标识(不生成值)。因此,您需要创建用户,然后创建一个Employe,其中设置之前创建的用户的“User”属性。 (主要思想是你需要手动初始化对外键的引用)

User user = new User{...};
Employee employe = new Employee{User = user, ...};
context.Add(employee);
context.SaveChanges();

或者您可能会使用层次结构。 (我没有在3级检查,但在2级这完全正常)。

public class User
{
    [Key]
    public int Id { get; set; }
    public string Username { get; set; } 
    public DateTime? LoginDate { get; set; }
    public bool IsActive{ get; set; }    

    public ICollection<Role> Roles { get; set; }
}

public class Employee : User
{
    public string Name{ get; set; }
    public string Email { get; set; }
}

public class Operator : Employee
{

}
© www.soinside.com 2019 - 2024. All rights reserved.