这个问题在这里已经有了答案:
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/