在通用存储库方法实体框架错误 [英] Error in generic repository method for Entity Framework

查看:111
本文介绍了在通用存储库方法实体框架错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创造我为我的库基类使用一个通用的方法,我有一个问题。这里的方法......

 公众实际的t第一(System.Linq.Ex pressions.Ex pression< Func键< T,布尔>>其中,名单,其中,串>属性)
    {
        IQueryable的< T>查询= NULL;
        如果(其中!= NULL)
        {
            查询= _context.CreateQuery< T>(的String.Format([{0}]中的typeof(T).Name.ToString())),其中(哪里);
        }
        其他
        {
            查询= _context.CreateQuery< T>(的String.Format([{0}]中的typeof(T).Name.ToString()));
        }

        的foreach(字符串s的属性)
        {
            查询= query.Include(多个);
        }

        牛逼_result =(T)query.First();

        返回_result;
    }
 

当我运行code它给了我这个错误:

  

公司不能在被解析   当前范围或上下文。使   确保所有的引用变量   在范围,即所需模式是   加载,并且命名空间   正确引用。近逃脱   标识符,第1行,第1列。

我有它为什么这样的想法,我只是不知道如何解决它。我认为它这样做是因为我的ObjectContext不知道对象公司,但它确实知道公司。关于如何解决这一问题?任何想法

该错误在这条线发生的:

  

T _result =(T)query.First();

谢谢!

解决方案

尝试使用

 查询= _context.CreateObjectSet< T>(),其中(哪里);
 

而不是

 查询= _context.CreateQuery< T>(的String.Format([{0}]中的typeof(T).Name.ToString())),其中(哪里) ;
 

I'm trying to create a generic method to use in my base class for my repositories and I'm having an issue. Here's the method...

        public virtual T First(System.Linq.Expressions.Expression<Func<T, bool>> where, List<string> properties)
    {
        IQueryable<T> query = null;
        if (where != null)
        {
            query = _context.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name.ToString())).Where(where);
        }
        else
        {
            query = _context.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name.ToString()));
        }

        foreach (string s in properties)
        {
            query = query.Include(s);
        }

        T _result = (T)query.First();

        return _result;
    }

When I run the code it gives me this error:

'Company' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. Near escaped identifier, line 1, column 1.

I have an idea on why it's doing this, I just don't know how to fix it. I think it's doing it because my ObjectContext doesn't know about the object "Company" but it does know "Companies". Any ideas on how to fix this??

The error happens on this line:

T _result = (T)query.First();

Thanks!

解决方案

Try to use

 query = _context.CreateObjectSet<T>().Where(where);

instead of

 query = _context.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name.ToString())).Where(where);

这篇关于在通用存储库方法实体框架错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆