简体   繁体   中英

DbSet.Add to ignore properties that is not set

Using EFCore, the model has a table with a foreign key constraints, it refers to another table, but this column is nullable . Models like this:

public class Order
{
    [Key]
    public int Id { get; set; }
    public int Code { get; set; }
    public int Amount { get; set; }
    ... // other fields
}
public class OrderCode
{
    [Key]
    public int Id { get; set; }
    public int Code { get; set; }
    public string Description { get; set; }
}

Order o = new Order { Amount = 1 }; // Code is not set and default NULL in DB
orders.Add(o);
db.SaveChanges(); // failure

So for some case the Code is empty and it is default NULL in database, but when I add the objects via DbSet.Add , it threw an exception:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Orders_Code". The conflict occurred in database "Store", table "dbo.OrderCode", column 'Id'.

It looks EFCore will try to add this field in insert statement even it is not set, so is there any way to avoid that?

I think you should use int? for Code in your model. Default value for int is 0 so entity framework sets that for Code field.

public class Order
{
    [Key]
    public int Id { get; set; }
    public int? Code { get; set; }
    public int Amount { get; set; }
    ... // other fields
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM