【发布时间】: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