Suppose I have the following model classes in the First-Framework Framework-First setup:
public class Person { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Team> Teams { get; set; } } public class Team { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<Person> People { get; set; } }
The database created from this code includes a TeamPersons table representing relationships between many people and teams between many.
Now suppose that I have a disabled Person object (not a proxy server and not yet context bound) whose team collections contain one or more disabled Team objects, all of which are commands already in the database. An object, for example, will be created as follows, for example, if a Person with identifier 1 and a command with Id 3 already existed in db:
var person = new Person { Id = 1, Name = "Bob", Teams = new HashSet<Team> { new Team { Id = 3, Name = "C Team"} } };
What is the best way to update this object so that after the update, the TeamPersons table contains one row for Bob, linking it to the C Team? I tried the obvious:
using (var context = new TestContext()) { context.Entry(person).State = EntityState.Modified; context.SaveChanges(); }
but the collection of commands is simply ignored. I have also tried different things, but it seems nothing like what I am doing here. Thanks for any help.
EDIT:
So, I get that I could get both the identity and the [s] command from db, update them and then commit the changes:
using (var context = new TestContext()) { var dbPerson = context.People.Find(person.Id); dbPerson.Name = person.Name; dbPerson.Teams.Clear(); foreach (var id in person.Teams.Select(x => x.Id)) { var team = context.Teams.Find(id); dbPerson.Teams.Add(team); } context.SaveChanges(); }
It is a pain if Person is a complex entity. I know that I could use Automapper or something to make things a little easier, but still it seems a shame if there is no way to save the original person object, instead of getting a new one and copying all the properties on top ...
c # entity-framework many-to-many dbcontext ef-code-first
Duncan
source share