实体框架6:通用方法AddOrUpdate

本文关键字:方法 AddOrUpdate 框架 实体 | 更新日期: 2023-09-27 18:12:26

我花了很多时间试图实现一个通用的方法来添加或更新一个实体与一个相关的实体(关系一对多),但我卡住了…

方法必须接收2个参数,第一个是父类,第二个是子类。目标是将子实体保存为父实体(添加不存在的或更新)

有一个泛型方法签名:

    public static bool AddOrUpdate<T,U>(T ItemToSave,U ItemRelated, int ID) where T : class where U : class
    {
        using (var context = new dbContext())
        {                
            var parent = context.Set<T>().Find(ID);
            if (parent == null) return;
            // how to retrieve now the child (ItemRelated) from the parent (ItemToSave) in order to add into it or update ?
            return context.SaveChanges() > 0;
        }
    }

这个方法位于一个静态类Service中我想打电话给服务中心。AddOrUpdate(Order _order, OrderLine _orderline, _order. orderid) from any class.

我被困在从父检索子,并添加或更新到它。

谁能帮我实现这个目标?

实体框架6:通用方法AddOrUpdate

在给定的约束条件下,这是不可能的。仔细想想——你给的唯一约束是每个都必须是一个类。这并不能保证存在父子关系,更不用说如何定义这种关系了。

泛型不是魔法。它们只是允许您以预定义的方式处理项目。在我们编写泛型方法之前,交互的定义必须存在。

你的ItemRrelated应该实现一些带有parentId属性的接口。然后你可以把它添加到DbSet,如果它还不存在。

var existingItemRelated == context.Set<U>().SingleOrDefault(ir => ir.ParentId == ItemRelated.ParentId && (/*your criteria to determine if child item equals the one in DB*/));

如果不存在则添加或编辑

编辑

如果你不想为有父项的实体提供公共接口,你可以向这个方法传递表达式,确定子实体是否有相同的父

public static bool AddOrUpdate<T, U>(T ItemToSave, U ItemRelated, int ID, Expression<Func<U,bool>> sameParentsExpression) where T : class where U : class
{
    using (var context = new dbContext())
    {
        var parent = context.Set<T>().Find(ID);
        if (parent == null) return false;
        // how to retrieve now the child (ItemRelated) from the parent (ItemToSave) in order to add into it or update ?
        var existingItemRelated = context.Set<U>()
                                    .Where(sameParentsExpression)
                                    .SingleOrDefault(/*your criteria to determine if child item equals the one in DB*/);
        return context.SaveChanges() > 0;
    }
}

和调用

AddOrUpdate(order, orderline, order.OrderId, ol => ol.OrderId == order.OrderId)