实体用户名已被占用

时间:2014-07-11 18:59:33

标签: c# asp.net entity-framework asp.net-mvc-5

我有以下两个课程:

public class ApplicationUser : IdentityUser
{
    public string Email { get; set; }
    public DateTime BirthDate { get; set; }
    public virtual ICollection<Arrayt> Arrayts { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<Tsk> Tsks { get; set; }
    public DbSet<Arrayt> Arrayts { get; set; }
    public DbSet<Comment> Comments { get; set; }
}

代表矩阵的类,可能有多个用户。

namespace WebPlanerZ.Models
{
  public class Arrayt
  {
    public Arrayt() { }
    public Arrayt(ApplicationUser user, string name, DateTime start)
    {
        Users = new HashSet<ApplicationUser>();
        Users.Add(user);
        ...
    }

        ...

    public virtual ICollection<ApplicationUser> Users { get; set; }
    public virtual ICollection<Tsk> Tsks { get; set; }
  }
}

在控制器的方法中,我想添加和删除给定矩阵的用户。 db.Arrays.Find(arrayId).Users.Add(added.Single())抛出异常

  

已经采用实体用户名

当我保存对数据库的更改时。感谢您的帮助。

public void UpdUsers(List<ApplicationUser> users, int arrayId)
{
        if (users != null && users.Count != 0)
        {
            var equalityComparer = new MyClassEqualityComparer();
            var deleted = db.Arrayts.Find(arrayId).Users.Except(users, equalityComparer).ToList();
            var added = users.Except(db.Arrayts.Find(arrayId).Users, equalityComparer).ToList();

            if (deleted.Count != 0)
                db.Arrayts.Find(arrayId).Users.Remove(deleted.Single());

            if (added.Count != 0)
                db.Arrayts.Find(arrayId).Users.Add(added.Single());

            try
            {
                db.SaveChanges();
            }
            catch (Exception exception)
            {
            }
        }
    }

0 个答案:

没有答案