imdadhusen
imdadhusen

Reputation: 2494

How to execute function in MVC with Entity Framework?

how to use following function

Generic Function:

public T GetSingle(Expression<Func<T, bool>> whereCondition)
       {
           return this.ObjectSet.Where(whereCondition).FirstOrDefault<>();
       }

Business logic wise:

//Now in the following function i would like to call Generic function.

public TabMasterViewModel GetSingle(Expression<Func<TabMasterViewModel, bool>> whereCondition)
       {

           _tabmasterRepository.GetSingle( .. what should be here.. );
       }

//Calling function from Controller level.

public ActionResult Details(int id)
       {
           return View(_tabmasterService.GetSingle(x => x.colID == id));
       }

I could not able to use the function, please suggest.

_tabmasterRepository.GetSingle( .. what should be here.. );

Thanks, Imdadhusen

Upvotes: 0

Views: 740

Answers (1)

Eranga
Eranga

Reputation: 32447

Either you modify your first generic function as

public T GetSingle(Expression<Func<T, bool>> whereCondition)
{
     return context.CreateObjectSet<T>().Where(whereCondition).FirstOrDefault();
}

or create a genetic repository

public class RepositoryGeneric<TEntity>
{
    public RepositoryGeneric(Context context)
    {
        Context = context;         
    }

    protected ObjectContext Context { get; private set; }

    protected virtual ObjectSet<TEntity> ObjectSet
    {
        get { return Context.CreateObjectSet<TEntity>(); }
    }

    public virtual TEntity GetByKey(params object[] keys)
    {
        return DbSet.Find(keys);
    }

    public TEntity GetSingle(Expression<Func<TEntity, bool>> whereCondition)
    {
        return ObjectSet.Where(whereCondition).FirstOrDefault();
    }
}

Edit:

using the generic function

TabMasterViewModel model = _tabmasterService.GetSingle(x => x.colID == id);

or using generic repository

var tabmasterRepository = new RepositoryGeneric<TabMasterViewModel>(new Context());
var model = tabmasterRepository.GetSingle(x => x.colID == id);

Upvotes: 1

Related Questions