Entity Framework 6 查询时上下文重复

Entity Framework 6 Context duplicate while query

我有一些我无法解决的问题。在我的项目中,我使用 EF6 Code First。我创建了一些模型,但它们的头是用户模型:

 public class User
{
    [Required]
    public Guid Id { get; set; }
    [Required, MaxLength(20), MinLength(5), UniqProp] 
    public string Login { get; set; }
    [Required, MaxLength(20), MinLength(8)]
    public string Password { get; set; }
    [Required]
    public Role Role { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required, UniqProp]
    public string Email { get; set; }
    [Required]
    public string City { get; set; }
    public virtual List<Ticket> Tickets { get; set; } 
}

我还创建了自己的上下文,如下所示:

public class TheatreContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<Ticket> Tickets { get; set; }
    public DbSet<Play> Plays { get; set; }
}

在此之后我以这种方式初始化我的数据库:

 using (var db = new TheatreContext())
 {
      Adding objects to db and save changes.
 }

那时一切正常。所有数据都添加到数据库中。然后我决定创建我的 Repository class 以使用 db:

进行一些操作
public class TheatreRepository<T> : IRepository<T> where T: class
{
    private readonly TheatreContext _context;
    private readonly DbSet<T> _dbSet;

    public TheatreRepository()
    {
        _context = new TheatreContext();
        _dbSet = _context.Set<T>();
    }

    public void Add(T entity)
    { 
        _dbSet.Add(entity);
    }

    public DbSet<T> GetAll()
    {
        return this._dbSet;
    }

    public void Commit()
    { 
        _context.SaveChanges();
    }

当我尝试以这种方式添加新用户时:

var repo = new TheatreRepository<User>();
var roleRepo = new TheatreRepository<Role>();

var newUser = new User
                  {
                      Id = Guid.NewGuid(),
                      Login = "Lionqweq",
                      City = "Minsk",
                      Role = roleRepo.GetAll().First(role => role.RoleType == RoleType.User),
                      FirstName = "Alex",
                      Email = "AlexDanger@gmail.com",
                      Password = "dsas1qsqda",
                      LastName = "Ivanov"
                  };
repo.Add(newUser);
repo.Commit();

在调用 CommitSaveChanges in db)时它会抛出 DbUpdateException 因为我试图用现有的 ID 添加到 Role table 对象。这对我来说没有意义!实际上我没有添加任何角色,我尝试只添加 User

我的 Role table 本地包含:

我的 Users table 本地有:

请大家提出建议和想法!我被深深地迷惑了[=​​26=]

你的问题在这里

public TheatreRepository()
{
    _context = new TheatreContext();
    _dbSet = _context.Set<T>();
}

如果您正在实施存储库模式,那么您的存储库 class 必须在构造函数中获取上下文,这被称为 DI,所以它必须像那样

public TheatreRepository(TheatreContext context)
{
    _context = context;
    _dbSet = _context.Set<T>();
} 

说明:

存储库必须使用相同的上下文来跟踪发生的更改和加载的(本地)实体,因此请考虑在存储库之前声明您的上下文,如下所示:

var db = new TheatreContext();
var repo = new TheatreRepository<User>(db);
var roleRepo = new TheatreRepository<Role>(db);
var newUser = new User
{
    Id = Guid.NewGuid(),
    Login = "Lionqweq",
    City = "Minsk",
    Role = roleRepo.GetAll().First(role => role.RoleType == RoleType.User),
    FirstName = "Alex",
    Email = "AlexDanger@gmail.com",
    Password = "dsas1qsqda",
    LastName = "Ivanov"
};
repo.Add(newUser);
repo.Commit();

你应该尝试而不是

[Required]
public Role Role { get; set; }

要使用也请使用对 FK 的引用:

[Required]
public Guid RoleId { get; set; }
public virtual Role Role { get; set; } 

创建新用户时仅设置 RoleId

这是一个例子: EF first code