简体   繁体   中英

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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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