我有以下实体与他们的关系。
public class User {
[Key]
public int UserId {get;set;}
...
}
public class Profile {
[Key]
public int ProfileId {get;set;}
[Required]
public virtual User User {get;set;}
}
现在,当我想要更新个人资料时,我会通过ProfileId检索它,应用我的更改然后调用SaveChanges()
。
问题是EF抱怨需要属性User
。我知道当我检索Profile时EF不会加载它。
但是,如何在不影响或加载用户的情况下更新个人资料?
请注意我正在使用Generic Repository模式,并希望在我的Repository<T>
中使用一个方法告诉EF在可能的情况下忽略任何给定的属性。
类似于MyRepository<T>.IgnorePropertyForUpdate(T entity, ??? property )
感谢Adv。
答案 0 :(得分:3)
问题是你没有Poco可访问的FKid用户 EF知道用户是必需的。你没有提供记录。 如果您已声明外键ID,即userId 然后你会在保存时获得Id。 只要关键是,EF就可以处理整个记录不存在的事实。
public class Profile {
[Key]
public int ProfileId {get;set;}
[Required]
[ForeignKey("User")]
Public int UserId {get;set}
public virtual User User {get;set;}
}
答案 1 :(得分:0)
所需的注释检查在保存更改之前必须加载用户。它是数据库中的约束(数据库表Profile-&gt; Column(User)allow null = false )
因此,您必须将用户包含在存储库中的Profile实体中,例如,如果您使用的是Daynmic库MyUserRepository.Include("User");
如果您直接这样做,可以这样做:
context.Prfiles.Include(p => p.User)....ToList();