我正在研究EF 5 Code-First解决方案,我正在尝试使用Repository模式更新现有实体并使用已修改的实体:
public void UpdateValues(T originalEntity, T modifiedEntity)
{
_uow.Context.Entry(originalEntity).CurrentValues.SetValues(modifiedEntity);
Run Code Online (Sandbox Code Playgroud)
我的简化域对象如下所示:
public class PolicyInformation : DomainObject
{
//Non-navigation properties
public string Description {get;set;}
public bool Reinsurance {get;set;}
...
//Navigation properties
LookupListItemFormType FormType {get;set;}
...
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是该CurrentValues.SetValues(modifiedEntity);方法似乎只更新标量和复杂类型属性,但不更新导航属性.我已经看到这种情况发生在很多人身上,但仍然不知道为什么会这样.但是,我发现如果我在执行后手动设置这些导航属性,UpdateValues一切正常:
_policyInfoRepo.UpdateValues(existingPolicyInfo, info);
existingPolicyInfo.FormType = info.FormType;
Run Code Online (Sandbox Code Playgroud)
问题是,因为我使用通用存储库:如何在域对象中获取导航属性列表?也许通过linq,反射或任何其他方式,以便我的存储库中的更新方法可以循环遍历它们并自动设置它们?
像这样的东西:
public void UpdateValues(T originalEntity, T modifiedEntity)
{
//Set non-nav props
_uow.Context.Entry(originalEntity).CurrentValues.SetValues(modifiedEntity);
//Set nav props
var navProps = GetNavigationProperties(originalEntity);
foreach(var navProp in navProps)
{
//Set originalEntity prop value to modifiedEntity value
}
Run Code Online (Sandbox Code Playgroud)
谢谢!