我正在使用EF Core 2.1
如何在EF Core中映射一对一关系。我有客户(Customer)
和课程(Course)
领域实体,其中一个客户将拥有一门课程。
这是我的Customer
& CoursePOCO
的样子。
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Course
{
public int Id { get; set; }
public string CouseName { get; set; }
public virtual Customer Customer { get; set; }
}
我正在使用FluentAPI。
public class CourseConfiguration : IEntityTypeConfiguration<Course>
{
public void Configure(EntityTypeBuilder<Parent> builder)
{
builder.HasKey(x => x.Customer.Id) //not allowing -> throws error
//The properties expression 'x => Convert(x.Customer.Id, Object)' is not valid.
// The expression should represent a simple property access: 't => t.MyProperty'.
// When specifying multiple properties use an anonymous type: 't => new { t.MyProperty1, t.MyProperty2 }'.
// Parameter name: propertyAccessExpression
}
}
由于是一对一的关系,我不想在联系人中创建额外的键(FK -CustomerId),
主要要求:-
我想将 Id
(在课程中)定义为 PK + FK
,并且在这个关系中客户是父实体。
例如,如果我是基于配置的迁移,我会按照以下方式操作:
public class Course
{
[Key]
[ForeignKey("Customer")]
public int Id { get; set; }
public string Name { get; set; }
public virtual Customer Customer { get; set; }
}
我想用EF Core的Fluent API来实现同样的事情,你能帮我翻译一下吗?
谢谢!