Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRUD operations with EntityFramework using generic type

I want to be able to use a generic service class of type T that will allow me to query the database dynamically. For example. Normally i would do something like this to delete a record

public void Delete(Post post)
{
    this._context.Posts.Remove(post);
}

I want to be able to do this

public void Delete(T post)
{
    this._context<T>.Remove(post);
}

I found an article here that sort of brushes over it, but if doesnt seem like a clean way to implement it. https://blog.magnusmontin.net/2013/05/30/generic-dal-using-entity-framework/

like image 520
Dan Hastings Avatar asked Apr 28 '17 10:04

Dan Hastings


1 Answers

You need DbContext.Set

https://msdn.microsoft.com/en-us/library/gg679544(v=vs.113).aspx

Returns a non-generic DbSet instance for access to entities of the given type in the context and the underlying store

public void Delete<T>(T post)
    where T : class
{
    this._context.Set<T>.Remove(post);
}

For later on, you can also query based on:

this._context.Set<T>.AsQueryable().Where(predicate);

In this instance predicate would be a Expression<Func<T, bool>>

So you can have a generic query method:

public IEnumerable<T> Query<T>(Expression<Func<T, bool>> predicate)
    where T : class
{
    return this._context.Set<T>().AsQueryable().Where(predicate).ToList();
}

... but I'm digressing from the question slightly now!

like image 106
Alex Avatar answered Sep 19 '22 11:09

Alex