【问题标题】:Fluent API one to one relationship mappingFluent API 一对一关系映射
【发布时间】:2015-06-24 19:49:14
【问题描述】:

我正在尝试使用 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 关系的映射吗?

谢谢

【问题讨论】:

  • 你为什么要使用 1:1 的关系 - 这实际上是将逻辑上的一张表一分为二。我很感激在某些情况下您会想要这样做 - 例如,如果有很多列 - 但在我看来,这应该保留为一个表。

标签: c# entity-framework ef-fluent-api


【解决方案1】:

在配置一对一关系时,Entity Framework要求依赖的主键也是外键,所以可以使用Data Annotations映射关系如下:

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方法用于更改数据库中的外键名称,但你的实体中不能有同名的属性,否则会抛出异常。

【讨论】:

  • 问题是我的 Person 对象和我的 Profl 对象都有他自己的 PK(它需要是这样的)是否有另一种方法来映射关系并保持不同的 Ids (PKs)。谢谢
  • 这对我有用,我只像这样添加了 MapKey:HasRequired(t => t.Profil).WithOptional(m => m.Person).Map(m => m.MapKey(" ProfileId"));
猜你喜欢
  • 1970-01-01
  • 2015-01-26
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
相关资源
最近更新 更多