开发者

Can you pass a LINQ table to a function?

I want to send a LINQ table (entity) as a parameter to a function to get a value in the select{}. The purpose is to return a value based on several properties of the table/entity, and I don't want all of the logic that determines the return value to be in the LINQ statement. Basically, is the line 'value = GetValue(tbl)' possible?

Public class MyClass
{
    public int value { get; set; }
}

//Some General function to determine return value from multiple properties
Private int GetValue(MyEntity cls)
{
    if (cls.var1 == 1)
        return var2;
    if (cls.var1 == 2)
        return cls.var2 - cls.var3;

    return -1;
}

Public List<MyClass> GetStuff(int iType)
{    
    List<MyClass> myClass = (from tbl in context.MyEntity
                             where tbl开发者_如何转开发.MyType == iType
                             select new MyClass
                             {
                                 value = GetValue(tbl)
                             }).ToList<MyClass>();
    return myClass;
}


LINQ to Entities is designed to convert the entire LINQ query into an equivalent SQL query that runs on the server so you should just use the functions and expressions that it knows how to translate to SQL. You can't just call arbitrary functions.

-This could be solved either by rewriting your calculation logic inside the LINQ query and this is the thing you mention you don't want.

-Another solution would be to add calculated properties to MyClass that rely on the data properties (var1, var2, var3,...) to be calculated.

-You could use something like the technique mentioned in this blog post: http://daniel.wertheim.se/2011/02/07/c-clean-up-your-linq-queries-and-lambda-expressions/ to put your logic in a central location outside the LINQ query.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜