Home > Software design >  How to update One to one entities in EF Core?
How to update One to one entities in EF Core?

Time:12-09

I have a strange problem with update related entities

First entity: Customers

public int CustId
public string CustName
public virtual CustomerType CustType
public int CustTypeId

Second entity (look-up table): CustomerType

public int CustTypeId
public string CustomerType

dbContext:



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);
            });

CustomerType table:

CustTypeId CustomerType
0 type_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();

when I try to save customer with CustomerType != 0 it's work fine. But then CustomerType = 0 (zero, not null) I get an error message:

The property 'CustomerType.CustTypeId' has a temporary value while attempting to change the entity's state to 'Unchanged'. Either set a permanent value explicitly, or ensure that the database is configured to generate values for this property.'

I use Net 6, EF core 6.0.10 & Postgres 14

I havn't any idea how to fix this problem

CodePudding user response:

Because the property type of int couldn't be null,it has a default value 0,0 may be treated as null under some circumstance You could try to set the propery as int? I tried and the results:

enter image description here

enter image description here

  • Related