Fluent Api: 1到0或两端1

本文关键字:Api Fluent | 更新日期: 2023-09-27 18:13:19

如何配置一个从1到0的关系或一个关系的两边。例如:

public class Student{
   public int Id {get; set;}
   public Registration Registration {get; set;}
}
public class Registration{
  public int Id {get; set;}
  //public int StudentId {get; set;}
  public Student StudentEntity {get; set;}
}

学生可以不注册而存在;注册也可以在没有学生的情况下创建。我能够配置注册像

HasOptional(o => o.StudentEntity).WithOptionalDependent(d => d.Registration ).Map(p => p.MapKey("StudentId"));

但是这需要我从模型中删除StudentId属性。然而,我需要这个来更新关系。因此,我如何配置这种关系并保持模型中定义的外键呢?

Fluent Api: 1到0或两端1

问题是在一个一对一的关系中,两个实体,主体和从属实体,必须共享相同的PK,并且从属实体的主键也必须是外键:

public class Principal
{
   [Key]
   public int Id {get;set;}
   public virtual Dependent Dependent{get;set;}
}
public class Dependent
{
  [Key,ForeignKey("Principal")]
  public int PrincipalId {get;set;}
  public virtual Principal Principal{get;set;}
}

在EF中,没有其他方法可以映射成一对一关系中的FK。

看到你的模型,也许你真正需要的是一对多的关系。我认为一个学生可以注册不止一次,在这种情况下,你的模型将是:
public class Student{
   public int Id {get; set;}
   public virtual ICollection<Registration> Registrations {get; set;}
}
public class Registration{
  public int Id {get; set;}
  public int StudentId {get; set;}
  public Student StudentEntity {get; set;}
}

关系配置为:

HasOptional(o => o.StudentEntity).WithMany(d => d.Registrations).HasForeignKey(o=>o.StudentId);