我正在使用web api 2并创建一个消息对象以保存到数据库。此消息对象需要将当前用户存储为应用程序用户类型。
我的代码如下所示:
var UserManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var currentUser = RequestContext.Principal;
var currentUserName = currentUser.Identity.Name;
var currentApplicationUser = UserManager.FindByName(currentUserName);
// I perhaps want to dispose of the user context?
// UserManager.Dispose();
globalMessage.sentBy = currentApplicationUser;
db.GlobalMessages.Add(globalMessage);
最后一行是抛出错误:An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
还有另一种解决方法吗?否则,我想,我可以调用一个获取当前用户的操作,将该用户作为arg重定向到该操作的另一个操作,然后执行更新?
答案 0 :(得分:1)
我解决了这个问题:
HttpContext
答案 1 :(得分:0)
问题是你是否已将db
上下文附加到已经附加到另一个活动的上下文实例的实体(currentApplicationUser
),因此解决方案可能是找到用户使用相同的上下文,在您的情况下,它将类似于:
var UserManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var currentUser = RequestContext.Principal;
var currentUserName = currentUser.Identity.Name;
var currentApplicationUser =db.AspNetUsers.FirstOrDefault(u=>u.UserName==currentUserName);
globalMessage.sentBy = currentApplicationUser;
db.GlobalMessages.Add(globalMessage);