简体   繁体   English

实体框架的通用存储库方法出错

[英]Error in generic repository method for Entity Framework

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. 近似转义标识符,第1行,第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". 我认为它正在这样做,因为我的ObjectContext不知道对象“公司”,但它确实知道“公司”。 Any ideas on how to fix this?? 有想法该怎么解决这个吗??

The error happens on this line: 错误发生在这一行:

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

Thanks! 谢谢!

Dan, get the entity set name with something like the following: Dan,获取实体集名称,如下所示:

string entitySetName = context.MetadataWorkspace
                        .GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace)
                        .BaseEntitySets.Where(bes => bes.ElementType.Name == typeof(T).Name).First().Name;

string name = String.Format("{0}.{1}", context.DefaultContainerName, entitySetName);

query = context.CreateQuery<T>(name).Where(where);

Doing this will resolve the proper plural name for the query. 执行此操作将解析查询的正确复数名称。

Using Yury's method would be the best option though. 使用Yury的方法将是最好的选择。

EDIT By the way, you should return FirstOrDefault() instead of First() in case the query returns no entities (it will throw an InvalidOperationException ). 编辑顺便说一句,如果查询没有返回任何实体(它将抛出InvalidOperationException ),你应该返回FirstOrDefault()而不是First() )。

Try to use 尝试使用

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

instead of 代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM