c# - 从实体集合属性中删除添加项目,并从其他列表中删除项目 ID
问题描述
我有用 C# 编写的旧遗留 .Net 代码,我需要解决这些问题......更好......而且更漂亮。今天我已经开始迁移到实体框架 6.44。我有一个大型实体(A),其中一些属性引用了实体(B)的集合。我获取 B 实体的 Id 列表,然后我需要更新集合,以便集合中的实体与 int 列表中的 Id 匹配。我的试用版一点都不好,但为了它我把它包括在内,希望你有更好的解决方案。我没有包含旧代码,因为制作数组和为下一个循环做很多事情。
// editACommand.B_Ids is cmd object with the ids of the B collection that need to bechanged.
var AEntity = DbContext.As.Include<Bs>.AsQuerable();
var resultBRemove = AEnitity.Bs.Where(p =>
editACommand.B_Ids != null &&
editACommand.B_Ids.All(p2 => p2 != p.Id)).ToList();
var resultBAdd = editACommand.SB_Ids.Where(p =>
AEnitity.Bs.Count > 0 &&
AEnitity.Bs.All(p2 => p2.Id != p)).ToList();
foreach (var resultBRemoveItem in resultBRemove )
{
AEnitity.Bs.Remove(resultBRemoveItem );
}
foreach (var resultBAddItem in resultBAdd )
{
var item = DBContext.AEnitity.SingleOrDefault(i => i.Id == resultBAddItem );
if (item != null)
{
AEnitity.Bs.Add(item);
}
}
DbContext.SaveChanges();
任何更好的解决方案都会是最好的,甚至会提出一个好的建议。
解决方案
推荐阅读
- nlp - TextBlob 拼写纠正需要很多时间
- python - 如何在python中进行计算?
- spring - Spring Boot 同时使用 2 个不同的 oauth 提供程序
- kubernetes - 具有 externalVaultAddr 权限的 Vault Injector 被拒绝
- groovy - 了解一个小型 groovy 脚本
- pandas - 为每个月制作新的子集
- flutter - 如何保存 TextField 输入值并将其提供给颤动的另一个屏幕?
- c - 循环内部和外部是否需要两个 scanf 或 getchar() ?
- python - 使for循环中的绘图标题成为数据框的列名
- laravel - vuetable-2 - 如何在 laravel/vuejs usig API 中将数据提取到表中