我正在关注此 https://learn.microsoft.com/en-us/ef/core/modeling/relationships/one-to-one 来学习如何处理 EF Core 中的 1:1 关系,但是当我的主类具有身份 pk 时,我遇到了麻烦,因为当我要保存 Id 默认值为 0 时,然后数据库解析该值,但如何将该值传递给子类?
// Principal (parent)
public class Blog
{
public int Id { get; set; }
public BlogHeader? Header { get; set; } // Reference navigation to dependent
}
// Dependent (child)
public class BlogHeader
{
public int Id { get; set; }
public int BlogId { get; set; } // Required foreign key property
public Blog Blog { get; set; } = null!; // Required reference navigation to principal
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasOne(e => e.Header)
.WithOne(e => e.Blog)
.HasForeignKey<BlogHeader>(e => e.BlogId)
.IsRequired();
}
如果没有关系,我可以像这样创建父级:
new Blog() { Id = 0 }
当 EF Core 保存更改时,数据库将
Id
设置为新的标识值,但如何将 Id
传递给子级,而无需单独创建它?
new Blog()
{
Id = 0,
Header = new BlogHeader() { Id = 0, BlogId = 0 }
}
当我尝试保存它时,EF Core 抛出有关
BlogId
FK 值的错误