如何在Entity Framework模型中引用用户对象?

时间:2017-01-22 04:24:39

标签: 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>();
    }
}

请注意,每个实体都有一些关联用户。在我的控制器中,我正在尝试将MyEntity的实例添加到数据库中,如下所示:

private ApplicationDbContext db = new ApplicationDbContext();

// ...

ApplicationUser currentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

MyEntity entityInstance = new MyEntity();
entityInstance.Id = Guid.NewGuid();
entityInstance.AssociatedUsers.Add(currentUser);
db.MyEntities.Add(entityInstance);
db.SaveChanges();

但是,该代码会引发以下错误:

  

IEntityChangeTracker的多个实例无法引用实体对象。

我从错误消息中收集CurrentUser仍然由支持ApplicationUserManager的数据库上下文管理,因此我无法将其添加到其他上下文中。但与other cases that I have found documented不同,我不能简单地切换上下文以便它们共享数据库连接:用户对象来自ApplicationUserManager。我需要做些什么来解决这个问题?我做了一些根本错误的事吗?我知道我可以使用ID而不是查找相应的用户,但我宁愿直接访问该对象。

1 个答案:

答案 0 :(得分:1)

您的问题与您发布的链接中发现的问题非常相似。简而言之,您无法从不同的上下文中操纵用户。这里:

ApplicationUser currentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

您实际上从currentUser获得了System.Web.HttpContext.Current.GetOwinContext(),但之后您尝试使用db保存ApplicationDbContext,这是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();

将它保持在相同的上下文中,您将解决问题:

IMAP4.__exit__