Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 怎么能 ;I ;在实体框架模型中引用用户对象?_C#_Asp.net_Asp.net Mvc_Entity Framework_Asp.net Identity - Fatal编程技术网

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();