ASP.NET MVC模型属性不在视图中返回null

时间:2011-03-14 06:07:06

标签: asp.net-mvc entity-framework

我有一个具有ICollection属性的EF Code First模型。

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中处理这种情况?

更新 数据来自存储库,例如。

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();

它现在正如预期的那样运作 - 但它看起来比应该的更多努力?

1 个答案:

答案 0 :(得分:0)

尝试急切加载 LinkedUserProfiles

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

看起来您正在使用存储库模式,因此不确定如何处理预先加载。我的存储库返回IQueryable<T>Include扩展方法可以解决这个问题。

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

相关问题