MVC/EF - Entity Relationship Not Being Saved
-
I'm working on a project in ASP.NET MVC, using Entity Framework 4 Code-First. The project uses the generic Repository pattern. I have an entity called "Tag", and "Tag" has a relation to entity "Right" (which is a collection). It looks like this:
public class Tag
{
public Tag()
{
this.Rights = new List();
}public string Name { get; set; } public virtual ICollection Rights { get; set; }
}
In the Tag controller, there is an action method for "Edit", similar to this (modified for simplicity):
public ActionResult Edit(Tag entity)
{
var rights = _rightsRepository.Get(r => r.IsActive == true).ToList();entity.Rights = rights; Repository.Update(entity); UnitOfWork.Commit(); return View("Index");
}
* "_rightsRepository" is "IRepository", which, using Dependency Injection, goes to "Repository" (generic Repository pattern). There is a Mapping class set up for Tags and Rights, and the mapping is setup like this:
// In the "TagMap" class
this.HasMany(t => t.Rights)
.WithMany(r => r.Tags)
.Map(m =>
{
m.ToTable("Tag_Right_Relation");
m.MapLeftKey("RightId");
m.MapRightKey("TagId");
}When debugging and setting a breakpoint in the "Edit" action method, I can step through, and the "Tag entity" has its property "entity.Rights" set accordingly, with the correct list of "Rights". However, when the actual update is called, the "Rights" collection is not persisted. However, when using a single database Context (e.g. "MyAppContext"), it saves properly. We have a similar relation set up for the entities "User" and "Role". It maps to "User_Role_Relation". That relation uses the exact same type of method for the Tag_Right_Relation above. The Tag_Right_Relation does not work. The User_Role_Relation DOES work. Why is it not working with objects from two different contexts for one entity type, but for another it does? EDIT: --------------------------- For whatever reason, it appears that the "Tag" entity is being disconnected from EF between the "Edit(int?)" action method, and the "Edit(Tag)" method. If I retrive the Tag entity from the Repository in "Edit(Tag)" and update the "Rights" collection, it works. Why is that? In other areas of the application, we don't have to do that.
djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run