簡體   English   中英

如何更新 EF Core 中的一對一實體?

[英]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

我不知道如何解決這個問題

因為int的屬性類型不能是null,它有一個默認值0,0在某些情況下可能會被當作null 你可以嘗試將屬性設置為int嗎? 我試過了,結果:

在此處輸入圖像描述

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM