[Update]
Because L2E is used you need to save all the linked objects first before you can save the main object. Which makes sense otherwise you would create (in my example) an artist without it's contact object. This isn't allowed by the database design.
[/Update]
Here's my implementation which worked.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Id")] Artist artist, [Bind(Prefix = "Contact")] Contact contact, [Bind(Prefix = "Country")] Country country, [Bind(Prefix = "ContactRelationship")] ContactRelationship contactRelationship)
{
ViewData["Countries"] = new SelectList(new CountryService(_msw).ListCountries().OrderBy(c => c.Name), "ID", "Name");
ViewData["ContactRelationships"] = new SelectList(new ContactRelationshipService(_msw).ListContactRelationships().OrderBy(c => c.ID), "ID", "Description");
country = _countryService.GetCountryById(country.ID);
contact.Country = country;
contactRelationship = _contactRelationshipService.GetContactRelationship(contactRelationship.ID);
contact.ContactRelationship = contactRelationship;
if(_contactService.CreateContact(contact)){
artist.Contact = contact;
if (_service.CreateArtist(artist))
return RedirectToAction("Index");
}
return View("Create");
}
And then in my ContactRepository :
public Contact CreateContact(Contact contact)
{
_entities.AddToContact(contact); //no longer throws the exception
_entities.SaveChanges();
return contact ;
}
I also found on this website that it is best to keep the same context throughout the application so I'm now using a special Data class for this:
public class Data
{
private static MyDBEntities _myDBEntities;
public static MyDBEntities MyDBEntities
{
get
{
if (_myDBEntities == null)
{
_myDBEntities = new MyDBEntities ();
}
return _myDBEntities;
}
set { _myDBEntities = value; }
}
}