【发布时间】:2012-01-21 01:18:06
【问题描述】:
我发现,如果我根据需要设置导航属性(使用 Required 属性)并使用延迟加载代理,当我加载父实体并且除了尝试保存在同一上下文中什么都不做时,会发生 EntityValidationError这就像“需要 xxx 字段”。
使用 Java 中的 hibernate 和 .NET 中的 NHibernate,可以只获取没有导航属性的实体(所有延迟加载),更新它并再次保存。框架意识到导航引用没有改变,也不会抛出任何错误。
示例如下
[Table("Address")]
public class Address
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AddressId { get; set; }
[Required, StringLength(512)]
public virtual string AddressLine1 { get; set; }
}
[Table("User")]
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
public string Name {get; set;}
[Required]
public virtual Address Address {get; set;}
}
void LoadAndSaveUser() {
var user = Context.Users.First();
user.Name = "foo";
// if i comment out this line
// ( probably EF fetches the lazy loaded entiy )
// the code works. it is strange though because i don't access any property/method of the Address
// var dummy = user.Address
Context.SaveChanges();
}
当我在地址属性上没有“必需”属性的情况下尝试此操作时,不会发生错误。使用Required 属性,我得到“地址字段是必需的!”。由于每个用户都应该有一个地址,我希望该属性创建一个一致的模型。
在一些论坛中,我发现一些帖子建议在加载父实体时包含导航属性(换句话说,急切加载),但如果我们有太多导航属性,这不是一种可行的方法。
我做错了什么还是有其他方法可以实现这种功能?
【问题讨论】:
标签: entity-framework ef-code-first