Given this extremely simple model:
public class MyContext : BaseContext
{
public DbSet<Foo> Foos { get; set; }
public DbSet<Bar> Bars { get; set; }
}
public class Foo
{
public int Id { get; set; }
public int Data { get; set; }
[Required]
public virtual Bar Bar { get; set; }
}
public class Bar
{
public int Id { get; set; }
}
The following program fails:
object id;
using (var context = new MyContext())
{
var foo = new Foo { Bar = new Bar() };
context.Foos.Add(foo);
context.SaveChanges();
id = foo.Id;
}
using (var context = new MyContext())
{
var foo = context.Foos.Find(id);
foo.Data = 2;
context.SaveChanges(); //Crash here
}
With a DbEntityValidationException
. The message found in EntityValidationErrors
is The Bar field is required..
However, if I force loading of the Bar
property by adding the following line before SaveChanges
:
var bar = foo.Bar;
Everything works fine. This also works if I remove the [Required]
attribute.
Is this really the expected behavior? Are there any workarounds (besides loading every single required reference every time I want to update an entity)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…