C# 怎么能 ;I ;在实体框架模型中引用用户对象?
我有以下型号:C# 怎么能 ;I ;在实体框架模型中引用用户对象?,c#,asp.net,asp.net-mvc,entity-framework,asp.net-identity,C#,Asp.net,Asp.net Mvc,Entity Framework,Asp.net Identity,我有以下型号: public class MyEntity { public Guid Id { get; set; } public virtual ICollection<ApplicationUser> AssociatedUsers { get; set; } public MyEntity() { AssociatedUsers = new HashSet<ApplicationUser>(); } }
public class MyEntity
{
public Guid Id { get; set; }
public virtual ICollection<ApplicationUser> AssociatedUsers { get; set; }
public MyEntity()
{
AssociatedUsers = new HashSet<ApplicationUser>();
}
}
但是,该代码会引发以下错误:
一个实体对象不能被多个IEntityChangeTracker实例引用
我从该错误消息中得知,
CurrentUser
仍由支持ApplicationUserManager
的数据库上下文管理,因此无法将其添加到其他上下文。但与之不同的是,我不能简单地切换上下文以便它们共享数据库连接:用户对象来自ApplicationUserManager
。我需要做什么来解决这个问题?我是不是做错了什么?我知道我可以使用ID来查找相应的用户,但我更希望直接访问该对象。您的问题与您发布的链接中发现的问题非常相似。简而言之,您无法从不同的上下文操纵用户。在这里:
ApplicationUser currentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
ApplicationUser currentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
var currentUser = db.Users.Find(System.Web.HttpContext.Current.User.Identity.GetUserId());
var entityInstance = new MyEntity();
entityInstance.Id = Guid.NewGuid();
entityInstance.AssociatedUsers.Add(currentUser);
db.MyEntities.Add(entityInstance);
db.SaveChanges();