【问题标题】:Generic function for getting data using entity framework使用实体框架获取数据的通用函数
【发布时间】:2015-09-24 04:42:16
【问题描述】:

我正在尝试创建一个通用函数来使用实体框架从数据库中获取数据。我正在传递一个id 作为检索的关键。为此,我编写了以下函数

public T Get<T>(object id) where T : class
{
    T item = null;

    using (var context = MyContext())
    {
        item = context.Set<T>().Find(id);
    }

    return item;
}

该功能运行没有任何问题。但是如果我没有将主键作为过滤器传递,我该如何修改这个函数来获取数据呢?

【问题讨论】:

    标签: c# entity-framework generics


    【解决方案1】:

    您可以传递谓词表达式并使用.FirstOrDefault()

    public T Get<T>(Expression<Func<T, bool>> predicate)
        where T : class
    {
        T item = null;
        using (var context = MyContext())
        {
            item = context.Set<T>().FirstOrDefault(predicate);
        }
        return item;
    }
    
    var customer = context.Get<Customer>(x => x.Name == "Bob");
    

    【讨论】:

    • 谢谢..这就是我要找的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多