I have a little problem with ASP.NET MVC and Entity Framework 4. I have an object called "UF" and the other is "Pais" and they have this relationship:
UF [* ... 0..1] Pais
I can access the Pais object directly from UF using the navigation property:
UF.Pais.Whatever = "foobar";
I currently have a view that inserts a new item into the database, and it has an editor for "Pais.Codigo" ("Codigo" is the main key for Pais). Therefore, when I insert a new UF, the environment creates an instance of the UF class with reference to an instance of the Pais class. Then it is done:
if (ModelState.IsValid) { db.UFs.AddObject(uf); db.SaveChanges(); return View(); }
The problem is that EF inserts the new Pais into the database, so it basically ignores the existing one.
For example, if my UF object has Pais with identifier 1. The current value of uf.Pais.Codigo is 1. Other attributes, such as the description, are currently zero. When I execute SaveChanges, both "uf" and "uf.Pais" have an "Added" state. The correct state for "uf.Pais" must be unchanged since it already exists in the database.
My question is: is there a way to change the default relationship of EntityState for Unchanged? The following code solves the problem, but adding it to each function with adding a new record to the database (and for each FK) is redundant!
db.ObjectStateManager.ChangeObjectState(uf.Pais, EntityState.Unchanged);
What is it. I'm not sure if I was clear enough. Feel free to ask for more information if necessary. And sorry for any English mistakes!
Thanks,
Ricardo
PS: "Pais" stands for country and "UF" for state.
Ricardo
source share