EF Core 中使用 Fluent API 的一对一关系

Kgn*_*web 4 c# entity-framework-core asp.net-core ef-core-2.1 entity-framework-migrations

我在用 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; }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)

由于它是一对一的关系,我不想在 Contact (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; }
 }
Run Code Online (Sandbox Code Playgroud)

我想在 EF Core 中使用 Fluent API 做同样的事情??

谢谢!!

itm*_*nus 6

正如其他答案所指出的,关键是使用该HasForeignKey<>()方法来配置外键。

但是要注意外键应该设置在依赖实体上,而不是主体实体上。

详细操作方法:

Coursefor添加导航属性Customer

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Course Course {get;set;} 
}
Run Code Online (Sandbox Code Playgroud)

现在将 设置Course.IdFK引用Customer.Id

public class AppDbContext : DbContext
{
    public AppDbContext (DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<Customer>(entity=>
        {
            entity.HasOne(customer=>customer.Course)
                .WithOne(course=> course.Customer)
                .HasForeignKey<Course>(course=>course.Id); 
        });
    }

    public DbSet<App.Models.Customer> Customer { get; set; }
    public DbSet<App.Models.Course> Courses{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)

生成的sql脚本是:

CREATE TABLE [Customer] (
    [Id] int NOT NULL IDENTITY,
    [Name] nvarchar(max) NULL,
    CONSTRAINT [PK_Customer] PRIMARY KEY ([Id])
);

GO

CREATE TABLE [Courses] (
    [Id] int NOT NULL,
    [CouseName] nvarchar(max) NULL,
    CONSTRAINT [PK_Courses] PRIMARY KEY ([Id]),
    CONSTRAINT [FK_Courses_Customer_Id] FOREIGN KEY ([Id]) REFERENCES [Customer] ([Id]) ON DELETE CASCADE
);

GO
Run Code Online (Sandbox Code Playgroud)