I have problem with updating entity related with application user in ASP.NET MVC. I have one-to-many relationship between ApplicationUser
and Order
. This is my entities and relation config:
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Order> HandlingOrders { get; set; }
}
public class Order
{
public int Id { get; set; }
//some properties
public string OperatorId { get; set; }
[ForeignKey("OperatorId")]
public virtual ApplicationUser Operator { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>().HasMany(n => n.HandlingOrders)
.WithOptional(n => n.Operator)
.HasForeignKey(n => n.OperatorId);
}
The problem is, when I try to save Order
in my controller, it fails with InvalidOperationException
and message
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
It happens because on one hand I use "Unit of Work" and "Generic Repository" to save Order
. From other hand I use ApplicationUserManager
to save ApplicationUser
.
public class OperatorController : Controller
{
private readonly UnitOfWork _unitOfWork;
private ApplicationUserManager _userManager
{
get { return HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
}
}
As a result I get two contexts: first is IOwinContext
from GetOwinContext()
, second is my regular ApplicationContext
, created (or is creating?) in "Unit of Work". And this contexts cause exception.
Could anyone suggest me, what is best in this situation? I fought about writing repository for ApplicationUser
, but I have never seen such practice in articles, so I am not sure.
Aucun commentaire:
Enregistrer un commentaire