首页 > 解决方案 > 添加父项或子项时 Blazor/EF 更新前端

问题描述

我有一个带有 EF 的 Blazor 站点。总体而言,一切都运行良好,但是当我向数据库添加条目时,我在更新前端时遇到了一些问题。

我有两个项目:

public class Supplier
{
    [Key]
    public int SupplierID { get; set; }
    [Required]
    public string Name { get; set; }
    public virtual List<SupplierContact> contactList { get; set; }
}
public class SupplierContact
{
    [Key]
    public int SupplierContactId { get; set; }
    public int SupplierID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

}

我使用 ContextFactory 填充它

using (var ctx = ContextFactory.CreateDbContext())
{
     suppliers = await ctx.Suppliers
          .Include(b => b.contactList).ToListAsync();
}

当我保存我的“供应商”项目时,我传递了原始供应商项目和更改值的 IDictionary。目前我使用以下代码:

async Task OnSupplierRowUpdatingAsync(Supplier dataItem, IDictionary<string, object> newValues)
{

    using (var ctx = ContextFactory.CreateDbContext())
    {
        //Create a new item, that is linked to the Passed item
        var entity = ctx.Suppliers.Find(dataItem.SupplierID);

        //Iterate each KVPair and update the new enitty with those values
        foreach (KeyValuePair<string, object> x in newValues)
        {
            entity.GetType().GetProperty(x.Key).SetValue(entity, x.Value);
        }
        entity.ModifiedOn = DateTime.Now;
        //Save the values to the databsae
        await ctx.SaveChangesAsync();

        //If no error's update the front end
        foreach (KeyValuePair<string, object> x in newValues)
        {
            dataItem.GetType().GetProperty(x.Key).SetValue(dataItem, x.Value);
        }
    }
}

此代码有效,但感觉有点“hacky”,因为我更新了单独的实体,然后更新了前端的实际供应商项目。

对我的问题:

  1. 这是更新后端和前端的最佳方法还是有更好的方法来做到这一点?
  2. 将项目添加为子项(SupplierContact)时,我使用类似的代码(但收到一个 SupplierContact 对象),但我不确定如何将此新实体分配给父项以便前端更新(数据库更新正常)

谢谢

标签: entity-framework-coreblazor-server-side

解决方案


推荐阅读