简体   繁体   English

EF代码首先插入或更新,返回T

[英]EF code first InsertOrUpdate with return T

I currently have a code which inserts or updates and return the affected entity but for now it is returning a specific type 我目前有一个代码,可以插入或更新并返回受影响的实体,但现在它返回的是特定类型

public delegate void BeforeTransaction(tbl_purchases_record x);

public static tbl_purchases_record insertupdate(
        tbl_purchases_record param,
        DB context, 
        Func<tbl_purchases_record,bool> lambda,
        BeforeTransaction beforetransaction = null)
 {

        var entity = context.tbl_purchases_record.SingleOrDefault(lambda);

        beforetransaction?.Invoke(entity); // callable parameter

        if (entity == null)
        {
            entity = context.tbl_purchases_record.Add(param);
        } 
        else
        {
            context.Entry(entity).CurrentValues.SetValues(param);
        }

        context.SaveChanges();
        return entity;
    }

is it possible to make this return dynamic type? 是否可以使此返回动态类型? (Also wanna ask...if is this a bad practice?) (也想问...这是不好的做法吗?)

Based on your comment: 根据您的评论:

Yes i can do that.. but my problem is context.tbl_purchases_record.SingleOrDefault(lambda)...i try context.Set(typeof(TEntity)) but this doesn't have SingleOrDefault 是的,我可以这样做..但是我的问题是context.tbl_purchases_record.SingleOrDefault(lambda)...我尝试使用context.Set(typeof(TEntity))但这没有SingleOrDefault

When using a generic method, the correct syntax to use is: 使用通用方法时,要使用的正确语法是:

context.Set<TEntity>().FirstOrDefault();

You simply pass the generic parameter. 您只需传递通用参数。

Putting it all together: 放在一起:

public T InsertUpdate<T>(T obj, DB context, Func<T,bool> lambda)
{
     var entity = context.Set<T>().SingleOrDefault(lambda);

    if (entity == null)
    {
        entity = context.Set<T>().Add(obj);
    } 
    else
    {
        context.Entry(entity).CurrentValues.SetValues(obj);
    }

    context.SaveChanges();
    return entity;
}

Also note that in newer versions of EF, there is actually an AddOrUpdate method that does the same thing: 还要注意,在较新版本的EF中,实际上有一个AddOrUpdate方法可以执行相同的操作:

context.Set<T>().AddOrUpdate(
                     lambda,       //How to identify a pre-existing item
                     obj           //The item with new values
                );

It will do the same thing. 它将做同样的事情。 If it finds a pre-existing item, it will update it. 如果找到预先存在的项目,它将对其进行更新。 Otherwise it will create a new item. 否则它将创建一个新项目。 However, this will not return the created/updated item and is therefore probably not what you want to use here. 但是,这将不会返回创建/更新的项目 ,因此可能不是您要在此处使用的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM