【问题标题】:DbSet.Add to ignore properties that is not setDbSet.Add 忽略未设置的属性
【发布时间】:2017-07-26 01:41:37
【问题描述】:

使用EFCore,模型有一个表有外键约束,它引用另一个表,但是这个列是可为空的。像这样的模型:

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

所以在某些情况下Code 是空的,它在数据库中是默认的NULL,但是当我通过DbSet.Add 添加对象时,它抛出了一个异常:

Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时出错。有关详细信息,请参阅内部异常。 ---> System.Data.SqlClient.SqlException:INSERT 语句与 FOREIGN KEY 约束“FK_Orders_Code”冲突。冲突发生在数据库“Store”、表“dbo.OrderCode”、列“Id”中。

看起来EFCore会尝试在插入语句中添加这个字段,即使它没有设置,那么有什么办法可以避免呢?

【问题讨论】:

    标签: c# asp.net entity-framework .net-core entity-framework-core


    【解决方案1】:

    我认为你应该使用 int?模型中的代码。 int 的默认值为 0,因此实体框架为 Code 字段设置该值。

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

    【讨论】:

    • 但是代码中使用该字段的任何地方都需要更新为 foo.Value,并且还要检查 foo.HasValue。有更好的选择吗?
    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2012-10-25
    • 2015-03-07
    • 2020-10-30
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    相关资源
    最近更新 更多