[英]How do I configure one-to-one relationship in EF Core if one of entities does not reference the other one?
[英]How to update One to one entities in EF Core?
我有一個關於更新相關實體的奇怪問題
第一實體:客戶
public int CustId
public string CustName
public virtual CustomerType CustType
public int CustTypeId
第二個實體(查找表):CustomerType
public int CustTypeId
public string CustomerType
數據庫上下文:
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<CustomerType> CustomerTypes { get; set; }
modelBuilder.Entity<Customer>(entity =>
{
entity.HasKey(e => e.CustId).HasName("customer_pkey");
entity.ToTable("customers", "x_customers");
entity.Property(e => e.CustId).HasColumnName("cust_id");
entity.Property(e => e.CustName).HasColumnName("cust_name");
entity.Property(e => e.CustTypeId).HasColumnName("cust_type_id");
entity.HasOne<CustomerType>().WithOne().HasForeignKey<Customer>(a => a.CustTypeId);
});
客戶類型表:
客戶類型 ID | 客戶類型 |
---|---|
0 | 類型_0 |
1個 | type_1 |
2個 | type_2 |
_dbContext.Customer.Add(customer);
_dbContext.Entry(customer.CustomerType).State = EntityState.Unchanged; //if not set this then EF try update CustomerType table
_dbContext.SaveChanges();
當我嘗試使用 CustomerType.= 0 保存客戶時,它工作正常,但是 CustomerType = 0 (zero: not null) 我收到一條錯誤消息:
在嘗試將實體的 state 更改為“未更改”時,屬性“CustomerType.CustTypeId”具有臨時值。 顯式設置永久值,或確保數據庫配置為為此屬性生成值。
我使用 Net 6、EF 核心 6.0.10 和 Postgres 14
我不知道如何解決這個問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.