gpt4 book ai didi

c# - 查询时 Entity Framework 6 上下文重复

转载 作者:搜寻专家 更新时间:2023-10-30 20:26:45 25 4
gpt4 key购买 nike

我有一些我无法解决的问题。在我的项目中,我使用 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 类来使用 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();

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

我的 Role 表在本地包含:

还有我在本地 Users 表中的内容:

enter image description here

请提出任何建议和想法!我深深地迷糊了

最佳答案

你应该尝试而不是

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

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

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

创建新用户时仅设置 RoleId

举个例子: EF first code

关于c# - 查询时 Entity Framework 6 上下文重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30478186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com