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

标签 c# asp.net-core entity-framework-core entity-framework-migrations ef-core-2.1

这个问题在这里已经有了答案:





One-to-Zero relationship with Entity Framework Core 2.0

(1 个回答)


2年前关闭。




我正在使用 EF Core 2.1
如何在 EF Core 中映射一对一关系。我有 Customer & Course一个客户将拥有一门类(class)的域实体。

这就是我的 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
    }
}

由于是一对一的关系,我不想在 Contact (FK -CustomerId) 中创建额外的键,

主要要求:-
我想定义 Id (在类(class)中)为 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 做同样的事情??

谢谢!!

最佳答案

正如其他答案所指出的,关键是使用 HasForeignKey<>() 配置外键的方法。
但是要注意外键应该设置在依赖实体上,而不是主体实体上。
详情:
Course 添加导航属性为 Customer

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Course Course {get;set;} 
}
现在设置 Course.Id作为 FK引用 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; }
}
生成的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

关于c# - EF Core 中使用 Fluent API 的一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53986595/

相关文章:

c# - 如何在 C# 中编辑 json 文件?

c# - 当数字存储为字符串时,从表中选择最大的数字?

c# - EF 核心 : How to reuse same expression in different query contexts

c# - 如何将字符串转换为 "iso-8859-1"?

c# - 多列索引搜索 Microsoft.Isam.Esent

c# - 在 Docker 中获取文件

c# - 我应该将使用 DDD 和 CQRS 方式刷新访问 token 的代码放在哪里?

asp.net-core - .NET Core 1.0开发安装VS2015工具报错

mysql - 在 ASP.NET Core 2.0 预览版中使用 Pomelo MySQL EF 提供程序时出错

c# - 使用 Table-Per-Hierarchy 继承模型访问相关实体的影子属性