开发者

How to execute function in MVC with Entity Framework?

开发者 https://www.devze.com 2023-03-10 21:38 出处:网络
how to use following function Generic Function: public T GetSingle(Expression<Func<T, bool>> whereCondition)

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 functi开发者_如何学JAVAon, please suggest.

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

Thanks, Imdadhusen


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号