【发布时间】:2011-03-14 06:07:05
【问题描述】:
我有一个 EF Code First 模型,它具有这样的 ICollection 属性。
public class AccountProfile
{
[Key]
public int AccountID { get; set; }
public string AccountName { get; set; }
public string Email { get; set; }
[Required]
public virtual ICollection<UserProfile> LinkedUserProfiles { get; set; }
}
我将一个编辑视图绑定到这个模型,但它只显示 AccountName 和 Email 属性。
我有一个 HttpPost ActionResult 来更新采用 AccountProfile 的模型。
发布时,AccountProfile 对象仅填充了 AccountName 和 Email 属性。 LinkedUserProfiles 为空。这意味着无法更新模型,因为需要 LinkedUserProfiles 属性。
我也尝试过类似以下的方法,但没有任何运气
var curAccountProfile = _accountProfileRepository.GetById(accountProfile.AccountID);
TryUpdateModel(curAccountProfile);
我做错了什么?这种情况在MVC中应该如何处理?
更新 数据来自存储库,例如。
var accountProfile = _accountProfileRepository.ById(1);
return View(accountProfile);
在加载视图之前检查 accountProfile 对象表明正在检索集合 - 因此这不是延迟加载未按预期工作的情况。
我已经实现了 AutoMapper,为视图创建了一个 ViewModel,并将我的代码更改为如下所示:
var accountProfile = _accountProfileRepository.ById(accountInformation.AccountID);
var result = _mappingEngine.Map<DisplayAccountInformationViewModel, AccountProfile>(accountInformation, accountProfile);
_unitOfWork.Commit();
它现在按预期工作 - 但似乎比应有的努力更多?
【问题讨论】:
-
您如何加载此编辑页面的数据?您可以发布您的查询方法吗?我认为问题在于延迟加载。
标签: asp.net-mvc entity-framework