C# 为什么此代码要更新用户';Asp.Net标识中的电子邮件地址是否导致主键重复?

C# 为什么此代码要更新用户';Asp.Net标识中的电子邮件地址是否导致主键重复?,c#,asp.net-mvc,entity-framework,asp.net-identity,C#,Asp.net Mvc,Entity Framework,Asp.net Identity,我有以下代码可以使用Identity framework的UserManager更新电子邮件地址: UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create())); ApplicationUser user = await UserManager.F

我有以下代码可以使用Identity framework的UserManager更新电子邮件地址:

UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
ApplicationUser user = await UserManager.FindByNameAsync(username);
IdentityResult result = null;
if (user != null)
{
    user.Email="foo";
    result = await UserManager.UpdateAsync(user);
}
UserManager UserManager=newusermanager(newuserstore(ApplicationDbContext.Create());
ApplicationUser user=await UserManager.FindBynameAAsync(用户名);
IdentityResult结果=null;
如果(用户!=null)
{
user.Email=“foo”;
结果=等待UserManager.UpdateAsync(用户);
}
但是,每当我尝试运行它时,它都会抛出以下错误:

System.InvalidOperationException:附加“ApplicationUser”类型的实体失败,因为相同类型的另一个实体已具有相同的主键值。如果图形中的任何实体具有冲突的键值,则在使用“Attach”方法或将实体状态设置为“Unchanged”或“Modified”时可能会发生这种情况。这可能是因为某些实体是新的,尚未收到数据库生成的键值。在这种情况下,使用“添加”方法或“添加”实体状态跟踪图形,然后根据需要将非新实体的状态设置为“未更改”或“已修改”


在大多数情况下,我只是使用了在VisualStudio中默认MVC模板中显示的现成标识框架。没有自定义用户存储或任何东西。我不确定我在这里做错了什么。

尝试将实体的状态更改为已修改的,如下所示:

var context = ApplicationDbContext.Create();
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
ApplicationUser user = await UserManager.FindByNameAsync(username);
IdentityResult result = null;
if (user != null)
{
    context.Entry(user).State = System.Data.EntityState.Modified;
    user.Email="foo";
    result = await UserManager.UpdateAsync(user);
}
var context=ApplicationDbContext.Create();
UserManager UserManager=newusermanager(newuserstore(context));
ApplicationUser user=await UserManager.FindBynameAAsync(用户名);
IdentityResult结果=null;
如果(用户!=null)
{
context.Entry(user.State=System.Data.EntityState.Modified;
user.Email=“foo”;
结果=等待UserManager.UpdateAsync(用户);
}

也许您已经有一个名为foo?@MXD的用户,我正在一个只有一个用户的数据库中测试它。此外,我还设置了配置选项以允许重复的电子邮件地址(它通过用户名标识用户,这与电子邮件不同)@Matthew,也许上面的答案有帮助?ApplicationDbContext上的.Create()方法是什么?不能说我以前见过它,在IdentityDbContext上找不到它的引用。。。