流畅的API一对一关系映射

本文关键字:关系 映射 一对一 API | 更新日期: 2023-09-27 17:59:27

我正在尝试使用Fluent API建立"一对一"关联。以下是我的课程:

public class Person
{
    public Guid Id { get; set; }
    public Guid ProfilId { get; set; }
    public DateTime InsertDate { get; set; }
    public DateTime UpdateDate { get; set; }
    public virtual Profil Profil { get; set; }
}
public class Profil
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public String Email { get; set; }
    public virtual Person Person { get; set; }
}
public class PersonMap : EntityTypeConfiguration<Person>  
{
    public PersonMap()
    {
        ...
        ToTable("Person");
        HasRequired(t => t.Profil)
              .WithOptional(c => c.Person)
              .Map(m => m.MapKey("ProfilId")); 
    }  
}

此实现抛出异常Invalid column name 'ProfilId'.

有人能告诉我如何使用这些类建立1-1关系的映射吗?

感谢

流畅的API一对一关系映射

在配置一对一关系时,实体框架要求依赖项的主键也是外键,因此您可以使用数据注释映射关系,如下所示:

public class Person
{
    [Key]
    [ForeignKey("Profil")]
    public Guid ProfilId { get; set; }
    public DateTime InsertDate { get; set; }
    public DateTime UpdateDate { get; set; }
    public virtual Profil Profil { get; set; }
}

或者使用Fluent Api:

  HasKey(t=>t.ProfilId);
  HasRequired(t => t.Profil).WithOptional(c => c.Person);

编辑1:

好吧,EF允许您在具有自己的PK的两个实体之间创建一对一关系,但您不能使用FK属性,因此,在Person实体中删除ProfileId,并以这种方式配置关系:

HasRequired(t => t.Profil).WithOptional(c => c.Person);

MapKey方法用于更改数据库中的外键名称,但实体中不能有同名的属性,否则将引发异常。