0
votes

I have an EF Code First model that has an ICollection property like so.

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; }
}

I'm binding an edit view to this model, but it only shows the AccountName and Email properties.

I have a HttpPost ActionResult to update the model that takes an AccountProfile.

When posting, the AccountProfile object only has the AccountName and Email properties populated. The LinkedUserProfiles is null. This means that the model cannot be updated as the LinkedUserProfiles property is required.

I have also tried something like the following without any luck

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

        TryUpdateModel(curAccountProfile);

What am I doing wrong? How should this circumstance be handled in MVC?

UPDATE The data was coming from a repository eg.

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

Inspecting the accountProfile object before the view was loaded shows that the collection is being retrieved - so it's not a case of lazy loading not working as expected.

I have since implemented AutoMapper, created a ViewModel for the view, and changed my code to be something like this:

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

It's working as expected now - but it seems like more effort than it should be?

1
How are you loading the data for this edit page ? Can you post your query method ? I think the problem is lazy loading. - BentOnCoding

1 Answers

0
votes

Try eager loading the LinkedUserProfiles:

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

Looks like you're using the Repository pattern, so not sure how you handle eager loading. My Repositories return IQueryable<T>, for which the Include extension methods works off.

If you're not using IQueryable<T>, then you might need to do the eager loading inside the Repository (such as accepting a boolean flag, e.g: GetById(int id, bool include profiles).