ASP.NET MVC 5身份应用程序用户作为外键 [英] ASP.NET MVC 5 identity application user as foreign key

查看:132
本文介绍了ASP.NET MVC 5身份应用程序用户作为外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Visual Studio 2013明天正式推出,希望会有更多的附带文档,特别是ASP.NET Identity。我正在跳跃,在此期间有人可以帮助我。



我所要做的是将当前登录的用户的UserID作为外键的外键表我叫零售商。



首先是我收到的错误消息


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


这是我的 {
[Key]
public int RetailerId {get;组; }
public string BusinessName {get;组; }
public string PhoneNumber {get;组; }
public string ManagerName {get;组; }
public Enums.Industry Industry {get;组; }
public virtual ApplicationUser UserProfile {get;组; }

}

下面是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);
等待db.SaveChangesAsync();
return RedirectToAction(Index);
}

为了充分披露这里有一些堆栈跟踪:

  InvalidOperationException:实体对象不能被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 do附件)+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
系统.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实体)+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(任务任务)+93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)+52
System.Runtime.CompilerServices.TaskAwaiter.GetResult()+21
lambda_method(Closure,Task)+ 64


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);
等待db.SaveChangesAsync();
return RedirectToAction(Index);

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


I know Visual Studio 2013 launches officially tomorrow and hopefully there will be more accompanying documentation especially as it regards ASP.NET Identity. I am hopping that in the meantime someone can help me out.

All I am trying to do is to get the UserID of the currently logged in user as foreign key to a table I called Retailer.

First here is the error message I am getting

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Here is my 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; }

}

Here is how Entity Framework CodeFirst created the table from the above class:

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

And here is where I am trying to save a record to this table in my Controller:

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

And for full disclosure here is some of the stack trace:

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

解决方案

UserManager uses it's own DbContext to load data from the database. You will need to retrieve the user from the same dbContext that you use to add a reference to. Something like:

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

Of course, you will have to retrieve the user from your DB using whatever method actually works for your models and DbContext.

这篇关于ASP.NET MVC 5身份应用程序用户作为外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆