2011-03-14 87 views
0

我有一个EF Code First模型,它具有类似的ICollection属性。ASP.NET MVC模型属性不在视图中返回null

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为null。这意味着模型无法更新,因为LinkedUserProfiles属性是必需的。

我也试着像下面这样没有任何的运气

 var curAccountProfile = _accountProfileRepository.GetById(accountProfile.AccountID); 

     TryUpdateModel(curAccountProfile); 

我在做什么错? MVC中应该如何处理这种情况?

UPDATE 该数据来自存储库,例如:

var accountProfile = _accountProfileRepository.ById(1); 
return View(accountProfile); 

检查的accountProfile对象视图加载显示,集合被检索之前 - 所以它不是延迟加载的预期不工作的情况下。

因为我已经实现AutoMapper,创建一个视图模型的视图,并改变了我的代码是这样的:

var accountProfile = _accountProfileRepository.ById(accountInformation.AccountID); 
var result = _mappingEngine.Map<DisplayAccountInformationViewModel, AccountProfile>(accountInformation, accountProfile); 
_unitOfWork.Commit(); 

它的工作像现在预期 - 但似乎更多的努力比它应该是?

+0

你是如何加载这个编辑页面的数据?你可以发布你的查询方法吗?我认为问题是延迟加载。 – BentOnCoding 2011-03-14 22:07:25

回答

0

尝试预先加载LinkedUserProfiles

var curAccountProfile = _accountProfileRepository 
    .GetById(accountProfile.AccountID) 
    .Include(ap => ap.LinkedUsedProfiles); 

看起来你使用Repository模式一样,所以不知道你是如何处理的立即加载。我的存储库返回IQueryable<T>,其中Include扩展方法关闭。

如果您不使用IQueryable<T>,那么您可能需要在存储库中进行急切加载(例如接受布尔标志,例如:GetById(int id, bool include profiles)。