Reputation: 118
I have a project that uses Entity Framework Code First and I'm running in the insert error "Cannot insert the value NULL into column". Here's my code
[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; }
}
And a Insert Method that uses AutoMapper to map a Dto into Foo entity.
public bool Insert(Foo obj)
{
Foo newFoo = this.MapFooEntity(obj);
this._context.Foo.Add(newFoo);
this._context.SaveChanges();
return true;
}
The Foo Object AutoMapper generates don't have any problems, it generate Foo with FooId = 0 and any child (Bar) with BarId = 0. In my view the EF should have see that BarId = 0 and attach the next indentity ID to it, but I'm getting that error. What are your thoughts guys ?
Upvotes: 1
Views: 431
Reputation: 36
Please try the following modification to your code:
In class Bar
, put [ForeignKey("FooId")]
before
public virtual Foo Foo { get; set; }
and put [InverseProperty("Foo")]
before
public virtual List<Bar> Bar { get; set; }
in class Foo
.
Upvotes: 2