【问题标题】:Problem with One To One Relation EF6 and primary key一对一关系 EF6 和主键的问题
【发布时间】:2019-04-14 21:07:27
【问题描述】:

我有 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】:

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

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

已存储在 ID 中。不需要复制。

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

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
{

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2011-10-03
    相关资源
    最近更新 更多