首页 > 解决方案 > 从实体集合属性中删除添加项目,并从其他列表中删除项目 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();

任何更好的解决方案都会是最好的,甚至会提出一个好的建议。

标签: c#performancelinqentity-framework-6one-to-many

解决方案


推荐阅读