繁体   English   中英

EF Core 5 一对多关系问题

[英]EF Core 5 One-to-many relationship problem

在这个例子中,一个用户有零个或多个账单,一个账单可以分配给一个用户。 也可以创建账单但从不分配。

public class User
{
  public int Id{ get; set; }   
  public List<Bill> bills{ get; set; }
}
        
public class Bill
{
  public int Id { get; set; }
        
  public int userId{ get; set; }
  public User user{ get; set; }
}

我还在我的数据库上下文配置中添加了这个:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
 modelBuilder.Entity<Bill>()
             .HasOne(b => b.user)
             .WithMany(u => u.bills)
             .HasForeignKey(b => b.userId);
}

我已经通过工作单元 + 存储库模式实现了这一点。 在我的BillService.cs ,我希望有一种方法可以让我更新/添加账单并将其分配给用户。

如果用户在数据库中不存在,它应该添加它。 如果用户存在,它应该更新它。

我尝试了两种方法。 第一的:

public async Task<void> AddUpdateBill(AddBillModel model){
    Bill bill= await unitOfWork.BillRepository.GetByID(model.billId);
    
    if( unitOfWork.UserRepo.GetById(model.userId) == null){
        unitOfWork.UserRepo.Insert(model.user);
    }else{
        unitOfWork.UserRepo.Update(model.user);
    }
    bill.user = model.user;
    unitOfWork.BillRepository.Update(bill);
    unitOfWork.Save();
}

第二:

public async Task<void> AddUpdateBill(AddBillModel model)
{
    Bill bill= await unitOfWork.BillRepository.GetByID(model.billId);
    bill.user = model.user;
    unitOfWork.BillRepository.Update(bill);
    unitOfWork.Save();
}

在这两种情况下,我都遇到了重复主键或已跟踪实体的问题。

哪个是最好的方法或正确的方法?

编辑:对不起,BillRepo 和 BillRepository 是相同的 class。

public async Task<Bill> GetByID(int id)
{
   return await context
           .bill
           .Include(b => b.user)
           .Where(b=> b.id == id)
           .FirstOrDefaultAsync();
}

public void Update(Bill bill)
{
   context.Entry(bill).CurrentValues.SetValues(bill);
}

第一种方法似乎更正确(对我来说)。 首先,遵守命名规则:所有属性必须以大写字符开头。 在您的情况下,“账单”、“用户 ID”、“用户”。

if( unitOfWork.UserRepo.GetById(model.userId) == null){
    unitOfWork.UserRepo.Insert(model.user);
}else{
    unitOfWork.UserRepo.Update(model.user);
}
bill.user = model.user;

你在这里不需要它

bill.user = model.user;

因为您刚刚将实体附加到上下文并更新/插入了它。

另外,不要忘记格式化您的代码,例如https://docs.microsoft.com/ru-ru/dotnet/csharp/programming-guide/inside-a-program/coding-conventions

考虑不直接从 model 插入/更新实体会很有用,例如:

if( unitOfWork.UserRepo.GetById(model.userId) == null){
    var user = new User 
    {
       //set properties
    };
    unitOfWork.UserRepo.Insert(user);
    unitOfWork.Save();
    bill.userId = user.Id;
}

这里:

if( unitOfWork.UserRepo.GetById(model.userId) == null){...

您从 UserRepo 检索用户,但不将其分配给任何变量。 这可能会导致异常,指出有多个具有相同 ID 的跟踪实体。

尝试检索(包括账单)或创建用户实体并在其中添加新账单。 然后将用户实体插入数据库(如果它不存在)并简单地Save您的工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM