6

我知道 Visual Studio 2013 将于明天正式发布,希望会有更多随附的文档,尤其是关于 ASP.NET 身份的文档。我希望同时有人可以帮助我。

我要做的就是获取当前登录用户的 UserID 作为我称为 Retailer 的表的外键。

首先是我收到的错误消息

一个实体对象不能被多个 IEntityChangeTracker 实例引用。

这是我的POCO

public class Retailer
{
    [Key]
    public int RetailerId { get; set; }
    public string BusinessName { get; set; }
    public string PhoneNumber { get; set; }
    public string ManagerName { get; set; }
    public Enums.Industry Industry { get; set; }
    public virtual ApplicationUser UserProfile { get; set; }

}

以下是 Entity Framework CodeFirst 如何从上述类创建表:

CreateTable(
    "dbo.Retailers",
    c => new
        {
            RetailerId = c.Int(nullable: false, identity: true),
            BusinessName = c.String(),
            PhoneNumber = c.String(),
            ManagerName = c.String(),
            Industry = c.Int(nullable: false),
            UserProfile_Id = c.String(maxLength: 128),
        })
    .PrimaryKey(t => t.RetailerId)
    .ForeignKey("dbo.AspNetUsers", t => t.UserProfile_Id)
    .Index(t => t.UserProfile_Id);

这是我试图在我的控制器中将记录保存到此表的地方:

if (ModelState.IsValid)
{
    var currentUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());
    retailer.UserProfile = currentUser;
    db.Retailers.Add(retailer);
    await db.SaveChangesAsync();
    return RedirectToAction("Index");
}

为了全面披露,这里是一些堆栈跟踪:

InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.]
   System.Data.Entity.Core.Objects.ObjectContext.VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity) +189
   System.Data.Entity.Core.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName) +126
   System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach) +98
   System.Data.Entity.Core.Objects.DataClasses.EntityReference.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach) +65
   System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach) +67
   System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach) +341
   System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach) +210
   System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach) +164
   System.Data.Entity.Core.Objects.ObjectContext.AddObject(String entitySetName, Object entity) +520
   System.Data.Entity.Internal.Linq.<>c__DisplayClassd.<Add>b__c() +97
   System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +355
   System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity) +200
   System.Data.Entity.DbSet`1.Add(TEntity entity) +130
   ValueCardPremium.Web.Controllers.<Create>d__7.MoveNext() in c:\Users\Valentine\Documents\Visual Studio 2013\Projects\ValueCardProjectPremium\ValueCardPremium.Web\Controllers\RetailerController.cs:70
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   lambda_method(Closure , Task ) +64
4

2 回答 2

13

UserManager 使用它自己的 DbContext 从数据库中加载数据。您将需要从用于添加引用的同一 dbContext 中检索用户。就像是:

var currentUMUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var currentUser = db.Users.Find(currentUMUser.UserID);
retailer.UserProfile = currentUser;
db.Retailers.Add(retailer);
await db.SaveChangesAsync();
return RedirectToAction("Index");

当然,您必须使用实际适用于您的模型和 DbContext 的任何方法从数据库中检索用户。

于 2013-11-12T18:01:36.607 回答
0

添加using语句:

using Microsoft.AspNet.Identity;

然后您可以使用以下方法检索 UserId:

var a = User.Identity.GetUserId();
于 2013-12-22T22:31:22.057 回答