简体   繁体   English

在 ASP.NET Core MVC 中从 ViewModel 更新 ICollection

[英]Updating ICollection from ViewModel in ASP.NET Core MVC

I am using ASP.NET Core MVC and EF6, and I am having trouble updating a many-to-many relationship.我正在使用 ASP.NET Core MVC 和 EF6,但无法更新多对多关系。 My model has an Asset table and a Group table.我的模型有一个资产表和一个组表。 The relationship between Assets and Groups is set as many-to-many. Assets 和 Groups 之间的关系设置为多对多。 Thus far, I have the following code that is able to assign groups to the assets through the AssetGroup table that EF automatically created.到目前为止,我有以下代码能够通过 EF 自动创建的 AssetGroup 表将组分配给资产。 It works when adding either a single group or multiple groups.它在添加单个组或多个组时起作用。

The problem is that when I want to update the assigned groups, it fails to properly remove old groups.问题是当我想更新分配的组时,它无法正确删除旧组。

Below is my code.下面是我的代码。

Models :型号

public class Asset : BaseEntity
{
    public Asset()
    {
        this.Group = new HashSet<Group>();
    }

    [Required]
    public string Name { get; set; }
    public string? Description { get; set; }
    public ICollection<Group>? Group { get; set; }
}

public class Group : BaseEntity
{
    public Asset()
    {
        this.Asset = new HashSet<Asset>();
    }

    [Required]
    public string Name { get; set; }
    public ICollection<Asset>? Asset { get; set; }
}

DbContext.cs: DbContext.cs:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    //new DBDesigner().ConfigureModels(modelBuilder);
    base.OnModelCreating(modelBuilder);

    // Many-to-many relationship with assets and groups
    modelBuilder
        .Entity<Asset>()
        .HasMany(p => p.Group)
        .WithMany(p => p.Asset)
        .UsingEntity(j => j.ToTable("AssetGroup"));
}

AssetCreateVM.cs: AssetCreateVM.cs:

public class AssetCreateVM
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
    public string? Description { get; set; }
    public List<int>? GroupIds { get; set; }
    public SelectList? Groups { get; set; }
}

AssetsController.cs:资产控制器.cs:

public async Task<IActionResult> Edit(int id, AssetCreateVM viewModel)
{
    if (ModelState.IsValid)
    {
        var model = mapper.Map<Asset>(viewModel);

        // Clear assigned groups from an asset if viewModel.GroupIds is empty
        if (viewModel.GroupIds == null)
        {
            // Remove existing group from the AssetGroup table
            model.Group.Clear();
            await assetRepository.UpdateAsync(model);
        }

        // Add new groups to AssetGroup table
        // Loop through the groupId
        foreach (var item in viewModel.GroupIds)
        {
            // Add group to the AssetGroup table
            var group = await groupRepository.GetAsync(item);
            if (group != null) model.Group.Add(group);
        }

        if (model.Group != null)
        {
            await assetRepository.UpdateAsync(model);
        }

        return RedirectToAction(nameof(Index));
    }

    viewModel.Groups = new SelectList(await groupRepository.GetAllAsync(), "Id", "Name", viewModel.GroupIds);

    return View(viewModel);
}

This is the UpdateAsync within the GenericRepository.cs这是GenericRepository.cs中的 UpdateAsync

public async Task UpdateAsync(T entity)
{
    _context.Update(entity);
    await _context.SaveChangesAsync();
}

As stated, the above code work as expected when adding either single or multiple groups to an asset.如前所述,将单个或多个组添加到资产时,上述代码按预期工作。 However, when I want to remove the assigned groups, the code no longer works.但是,当我想删除分配的组时,代码不再起作用。

The problem is in the following code:问题出在以下代码中:

if (viewModel.GroupIds == null)
{
    // Remove existing group from the AssetGroup table
    model.Group.Clear();
    await assetRepository.UpdateAsync(model);
}

It seems like the model.Group.Clear() is clearing out the Groups from Asset however, the UpdateAsync is not applying the changes to the database correctly.看起来 model.Group.Clear() 正在从资产中清除组,但是 UpdateAsync 没有正确地将更改应用到数据库。 ie the rows are not being removed from the AssetGroup table.即没有从 AssetGroup 表中删除行。

Why is the AssetGroup changes not being updated when I remove the group association?为什么删除组关联时 AssetGroup 更改未更新?

you should use RemoveRange or Remove instead Update for delete item您应该使用RemoveRangeRemove代替Update删除项目

Context.Assets.Group.RemoveRange(entities) // entites like model.Group

or或者

Context.Group.RemoveRange(entities)

If you can't access removerange you can do it as follows如果您无法访问 removerange ,您可以按如下方式进行

model.Group.ForEach(group => repo.Delete(group));

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

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