[英]EF Core 7 - how to set up multiple nullable GUID foreign keys on child object without triggering foreign key conflict
我有 3 個實體: Person
、 User
和Location
。
Person
可以有多個Locations
User
可以有多個Locations
我的實體設置如下:
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual IList<Location>? Locations { get; set; }
}
public class PersonEntityTypeConfiguration : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Person> builder)
{
builder
.HasMany(b => b.Locations)
.WithOne(b => b.Person)
.HasForeignKey(b => b.PersonId)
.IsRequired(false);
}
}
public class User
{
public Guid Id { get; set; }
public Guid? Username { get; set; }
public virtual IList<Location>? Locations { get; set; }
}
public class UserEntityTypeConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder
.HasMany(b => b.Locations)
.WithOne(b => b.User)
.HasForeignKey(b => b.UserId)
.IsRequired(false);
}
}
public class Location : UdbObject
{
public Guid Id { get; set; }
public string Description { get; set; }
[ForeignKey(nameof(Person))]
public Guid? PersonId { get; set; }
public virtual Person? Person { get; set; }
[ForeignKey(nameof(User))]
public Guid? UserId { get; set; }
public virtual User? User { get; set; }
}
問題:我試圖將一個User
插入到我的 SQL Server 數據庫中。 該用戶在其IList<Location>? Locations
中有一個Location
對象? IList<Location>? Locations
集合。 我收到以下錯誤: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Locations_Persons_PersonId".
這是哪里出錯了:既然Person.Id
是一個Guid?
對象,在提交給數據庫之前,它會自動設置為Guid.Empty
的等價物。 這會導致 FK 沖突,因為數據庫發現數據庫中沒有Person
對象的 Id 設置為Guid.Empty
的等價物。
我嘗試過的:我看到在以前版本的 EF Core 中,有一個.WithOptional()
方法可以在 Fluent API 中使用,但不幸的是,這個方法在 EF Core 7 中無法識別。我嘗試使用API 中的.IsRequired(false)
方法,從數據庫的角度來看它可能有效,但我的問題是基於 GUID 的Id
屬性在傳遞給數據庫之前在服務器上被設置為Guid.Empty
,所以.IsRequired(false)
沒有機會完成它的工作。
我錯過了什么嗎? 還有其他方法可以配置嗎?
解決方案:我有一個PersonDto
,它有一個屬性public Guid Id { get; set; }
public Guid Id { get; set; }
public Guid Id { get; set; }
而不是Guid?
並且它被映射回加載了Guid.Empty
的Person
對象。 呃。
只需讓它們成為 M2M 關系,外鍵就會全部在橋接表中。 例如
public class Location : UdbObject
{
public Guid Id { get; set; }
public string Description { get; set; }
public virtual ICollection<Person> Persons { get; } = new HashSet<Person>();
public virtual ICollection<User> Users { get; } = new HashSet<User>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.