首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实体框架核心6-多对多更新

实体框架核心6-多对多更新
EN

Stack Overflow用户
提问于 2022-02-07 23:55:55
回答 1查看 742关注 0票数 1

我试图在Server上为EF 6创建一个多到多的更新,但我真的很困惑。我有stock.cs类和location.cs

代码语言:javascript
复制
public class Stock : BaseModel 
{
    public Stock()
    {
        this.Locations = new List<Location>();
    }

    [Key] 
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Guid { get; set; } = string.Empty;
    public string RackBarNumber { get; set; } = string.Empty;
    public string ShelveNumber { get; set; } = string.Empty;
    public string ShelveName { get; set; } = string.Empty;

    public virtual List<Location>? Locations { get; set; }
}

public class Location : BaseModel
{
    public Location()
    {
        this.Stocks = new List<Stock>();
    }

    [Key] 
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string? Description { get; set; }

    public virtual List<Stock>? Stocks { get; set; }
}

我用这个作为我的DTO来获取我所有的当前位置

代码语言:javascript
复制
public class StockLocations
{
    public Stock Stock { get; set; }
    public virtual ICollection<Location> currentLocations { get; set; }
}

现在StockController是更新字段的代码,我可以在EF创建的StockLocation表中创建和删除。但是当我一次尝试许多更新的时候,它就会乱七八糟。

这是我最后一次尝试:

代码语言:javascript
复制
[HttpPut("{id}")]
public async Task<IActionResult> PutStock(int id, StockLocations stockLocation)
{
    await _userService.ConfirmUser(User);
        
    stockLocation.Stock.UpdatedAt = DateTime.Now;
        
    List<Location> removedLocations = new List<Location>();

    if (id != stockLocation.Stock.Id)
    {
        return BadRequest();
    }

    _context.Entry(stockLocation.Stock).State = EntityState.Modified;

    try
    {
        await _context.SaveChangesAsync();
            
        // Add new items to the database
        foreach (var item in stockLocation.Stock.Locations)
        {
            if (!stockLocation.currentLocations.Any(x => x.Id == item.Id))
            {
                _context.Entry(item).State = EntityState.Modified;
                await _context.SaveChangesAsync();
            }
        }
            
        // Create a list of removed locations to be removed from the database
        foreach (Location location in stockLocation.currentLocations)
        {
            if (!stockLocation.Stock.Locations.Any(x => x.Id == location.Id))
            {
                removedLocations.Add(location);
            }
        }

        foreach (var item in removedLocations)
        {
            /*
            Stock stock = _context.Stocks.Include(x => x.Locations).Single(x =>             x.Id == id);
            Location locationToDelete = stock.Locations.Find(x => x.Id == item.Id);

            stock.Locations.Remove(locationToDelete);
            await _context.SaveChangesAsync();
            */
        }
    }
    catch (DbUpdateConcurrencyException)
    {
        return NoContent();
    }

    return NoContent();
}

有谁愿意告诉我如何正确地处理这件事吗?

EN

回答 1

Stack Overflow用户

发布于 2022-02-08 00:15:18

由于您需要更新StockLocations,所以我建议您只需从数据库中提取记录,例如:

代码语言:javascript
复制
        var record = await  _context.StockLocations
            .Include(a=>a.Location).Include(a=>a.Stock)
            .FirstOrDefaultAsync(a=>a.id == id);  
    
        if(record == null) {
        thrown new NotFoundException(); 
        }  
    
    stockLocation.Stock.UpdatedAt = DateTime.Now; 
     await _context.SaveChangesAsync(); 

 // other code  
 // add new location to the db if they don't exist 
 var locations = stockLocation.Location; 
  foreach(var loc in locations) {
    var findLocation = 
    _context.Locations.FirstOrDefault(a=>a.Name.ToLower() == 
   loc.Name.ToLower()) ; 
   if(findLocation == null){
  // does not exist and can be added 
   } 

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71026928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档