views:

897

answers:

1

I'm trying to use the repository pattern to save an entity using the Entity Framework. I'm unclear on how to save the Navigation Properties (like Account below). Can anyone shed some light on this. Especially how one would set the AccountId from an MVC controller all the way through to the repository where it's saved.

Thanks!

--- Sample Code ---

public void SavePerson(Person person) {
if (person != null) { using (xxxxxxEntities bbEntities = new xxxxxxEntities()) { //see if it's in the db Person cPerson;

                ObjectQuery<Person> persons = bbEntities.Person;

                cPerson = (from p in persons
                         where p.PersonId == person.PersonId
                         select p).FirstOrDefault() ?? new Person();

                //synch it
                **cPerson.Account.AccountId = person.Account.AccountId;**
                cPerson.Active = person.Active;
                cPerson.BirthDay = person.BirthDay;
                cPerson.BirthMonth = person.BirthMonth;
                cPerson.BirthYear = person.BirthYear;
                cPerson.CellPhone = person.CellPhone;
                cPerson.CreatedBy = person.CreatedBy;
                cPerson.CScore = person.CScore;

Etc....

+3  A: 

I think you may be going about this the hard way. There are lots of posts on the repository pattern, the way that works best with MVC is to get the item, then update it with the form, then save it. What you're doing is passing the item through to your repository, getting it again and then updating it with the object.

But that's not the problem you asked about;

cPerson.Account = (from a in Account
                   where a.AccountId.Equals(person.Account.AccountId)
                   select a).FirstOrDefault();

You need to set the Account object to an instance of the account you're trying to reference like this. You could, and probably should, extract this code into a seperate repository for the account, just make sure they share the same Entity context.

Odd