【问题标题】:Cannot insert the value NULL into column EF Code First无法将值 NULL 插入列 EF Code First
【发布时间】:2016-05-22 15:25:52
【问题描述】:

我有一个使用 Entity Framework Code First 的项目,并且我在插入错误“无法将值 NULL 插入列”中运行。 这是我的代码

[Table("Foo")]
public class Foo
{
    [Key]
    public int FooId { get; set; }
    public string Name { get; set; }

    public virtual List<Bar> Bar { get; set; }
}

[Table("Bar")]
public class Bar
{
    [Key, Column(Order = 0), ForeignKey("Foo")]
    public int FooId{ get; set; }

    [Key, Column(Order = 1), DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int BarId { get; set; }
    public DateTime Date { get; set; }

    public virtual Foo Foo { get; set; }
}

还有一个使用 AutoMapper 将 Dto 映射到 Foo 实体的 Insert 方法。

    public bool Insert(Foo obj)
    {
        Foo newFoo = this.MapFooEntity(obj);
        this._context.Foo.Add(newFoo);
        this._context.SaveChanges();
        return true;
    }

AutoMapper 生成的 Foo 对象没有任何问题,它生成 FooId = 0 的 Foo 和 BarId = 0 的任何子 (Bar)。 在我看来,EF 应该看到 BarId = 0 并将下一个身份 ID 附加到它,但我收到了该错误。大家有什么想法?

【问题讨论】:

  • 哪里和哪一行抛出异常?在添加 Bar 或 Foo 时?

标签: c# entity-framework ef-code-first


【解决方案1】:

请尝试对您的代码进行以下修改:

Bar类中,把[ForeignKey("FooId")]放在前面

public virtual Foo Foo { get; set; }

并把[InverseProperty("Foo")]放在前面

public virtual List<Bar> Bar { get; set; }

在课堂上Foo

【讨论】:

    猜你喜欢
    • 2014-10-30
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多