C# - 在Select子句中选择可编程属性

时间:2012-09-26 00:35:39

标签: c# linq generics iqueryable

请原谅我提出这个问题的无知,因为我还在学习NHibernate和Linq。我做了一些搜索,但我不明白我的问题的解决方案是否可行

我有以下代码块:

// this function searches the database's table for a single object that matches the 'Name' property with 'objectName'
public static Object Read<T>(string objectName)
{
    using (ISession session = NHibernateHelper.OpenSession())
    {
        IQueryable<T> objectList = session.Query<T>(); // pull (query) all the objects from the table in the database
        int count = objectList.Count(); // return the number of objects in the table
        // alternative: int count = makeList.Count<T>();

        IQueryable<T> objectQuery = null; // create a reference for our queryable list of objects
        object foundObject = null; // create an object reference for our found object

        if (count > 0)
        {
            // give me all objects that have a name that matches 'objectName' and store them in 'objectQuery'
            objectQuery = (from obj in objectList where obj.Name == objectName select obj);

            // make sure that 'objectQuery' has only one object in it
            try
            {
                foundObject = objectQuery.Single();
            }
            catch
            {
                return null;
            }

            // output some information to the console (output screen)
            Console.WriteLine("Read Make: " + foundObject.ToString());
        }
        // pass the reference of the found object on to whoever asked for it
        return foundObject;
    }
}

除了一行之外,这一切都很棒: objectQuery = (from obj in objectList where obj.Name == objectName select obj);

这里的问题是我要求一个未知对象的“Name”属性,这不仅是不可能的,而且是错误的代码。

我真正想做的是指明我正在寻找属于T型对象属性的项目。

任何参赛者?

1 个答案:

答案 0 :(得分:2)

问题在于你正在编写一个泛型方法,这意味着它将接受任何类型的T.但实际上,当你写下:

where obj.Name == objectName

您期望某个特定类型或实现特定接口的类型,或者是从特定基类派生的。

您的方法应该更像:

public static T Read<T>(string objectName)
where T : ISomeInterface

请注意,我还将返回类型从Object更改为T,这对此方法的调用者更友好,并且无需将对象强制转换为T.