entity-framework-core - 添加父项或子项时 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”,因为我更新了单独的实体,然后更新了前端的实际供应商项目。
对我的问题:
- 这是更新后端和前端的最佳方法还是有更好的方法来做到这一点?
- 将项目添加为子项(SupplierContact)时,我使用类似的代码(但收到一个 SupplierContact 对象),但我不确定如何将此新实体分配给父项以便前端更新(数据库更新正常)
谢谢
解决方案
推荐阅读
- sql - SQL中的左右连接在一起
- android - RecyclerView 绘图问题
- python - 错误:命令'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe'
- unity3d - 如何在 Unity 的网格中执行布尔运算?
- reactjs - 将变量传递给容器内的 npm app
- python - aligning multiple signals with same shape but varying x's and y's (time and voltage)
- cmd - How do I echo parameter in batch file using a for loop
- ray - 如何在“火车”中间记录图像
- .net-core - Adfs 在 dotnet core aspboilerplate 上进行身份验证
- ios - Swift:模板定义中的常量