给定这个极其简单的模型:
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; }
}
以下程序失败:
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
}
使用DbEntityValidationException
。在EntityValidationErrors
中找到的消息是栏字段是必填项。
但是,如果我通过在SaveChanges
之前添加以下行来强制加载Bar
属性
var bar = foo.Bar;
一切都很好。如果我删除了[Required]
属性,这也是有效的。
这真的是预期的行为吗?有没有什么变通的方法(除了每次我想要更新一个实体时加载每一个需要的引用)
发布于 2012-10-13 15:22:08
这是一个semi-acceptable work-around
var errors = this.context.GetValidationErrors();
foreach (DbEntityValidationResult result in errors) {
Type baseType = result.Entry.Entity.GetType().BaseType;
foreach (PropertyInfo property in result.Entry.Entity.GetType().GetProperties()) {
if (baseType.GetProperty(property.Name).GetCustomAttributes(typeof(RequiredAttribute), true).Any()) {
property.GetValue(result.Entry.Entity, null);
}
}
}
发布于 2015-03-19 07:17:20
在EF 6.1.2中也有同样的问题。要解决这个问题,您的类应该如下所示:
public class Foo {
public int Id { get; set; }
public int Data { get; set; }
public int BarId { get; set; }
public virtual Bar Bar { get; set; }
}
正如您所看到的,不需要" required“属性,因为因为BarId属性不可为空,所以Bar属性已经是必需的。
因此,如果您希望Bar属性可以为空,则必须编写:
public class Foo {
public int Id { get; set; }
public int Data { get; set; }
public int? BarId { get; set; }
public virtual Bar Bar { get; set; }
}
https://stackoverflow.com/questions/6038541
复制相似问题