C# Fluent API一对一关系映射
我正在尝试使用fluentapi建立一个“一对一”的关联。以下是我的课程:C# Fluent API一对一关系映射,c#,entity-framework,ef-fluent-api,C#,Entity Framework,Ef Fluent Api,我正在尝试使用fluentapi建立一个“一对一”的关联。以下是我的课程: 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
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"));
}
}
公共类人物
{
公共Guid Id{get;set;}
公共Guid ProfilId{get;set;}
公共日期时间插入日期{get;set;}
公共日期时间更新日期{get;set;}
公共虚拟Profil Profil{get;set;}
}
公共类文件
{
公共Guid Id{get;set;}
公共字符串名{get;set;}
公共字符串MiddleName{get;set;}
公共字符串LastName{get;set;}
公共日期时间出生日期{get;set;}
公共字符串电子邮件{get;set;}
公共虚拟人{get;set;}
}
公共类PersonMap:EntityTypeConfiguration
{
公众人物地图()
{
...
可转让(“人”);
HasRequired(t=>t.profile)
.With可选(c=>c.Person)
.Map(m=>m.MapKey(“ProfilId”);
}
}
此实现引发异常无效列名“ProfilId”。
有人能告诉我如何使用这些类建立1-1关系的映射吗
谢谢在配置一对一关系时,实体框架要求依赖项的主键也是外键,因此您可以使用数据注释映射关系,如下所示:
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
方法用于更改数据库中的外键名称,但实体中不能有同名的属性,否则将引发异常。为什么要使用1:1关系-这实际上是将逻辑上的一个表拆分为两个。我很感激在某些情况下,您可能希望这样做—例如,如果有许多列—但在我看来,这应该作为一个单独的表。问题是,我的Person对象和我的Profl对象都有自己的PK(需要这样做),是否有其他方法映射关系并保留不同的ID(PK)。感谢为我工作的人,我只添加了MapKey,如下所示:HasRequired(t=>t.Profil).WithOptional(m=>m.Person).Map(m=>m.MapKey(“ProfilId”);