开发者

Calling functions in Linq To SQl .net 3.5

guys How can i achieve the following

var productslist=from p in productsTable
                 select new product{Id=p.Id,Tax=myfunctions.calculateTax(p.price)};

i have tried to google and came across t开发者_JAVA技巧his document. Is there another way i can do this without using third party dlls

Solution: Move application to .net 4.0 (this is actually support and supposed to work). Nway i stuck to the below solution for the time being


LINQ to SQL can't magically translate arbitrary C# to TSQL; a limited selection of commonly needed syntax is available inside LINQ, but a C# method is not going to work.

Options:

  • rewrite the function as a UDF (in TSQL) and map the UDF to your data-context (i.e. drag the UDF onto the designer surface); use myDataContext.MyUdf(args) in LINQ
  • apply your function only once the data is back in .NET-land
  • re-write the function as a LINQ-projection

I expect the middle option is the easiest in your scenario. For example:

var productslist=
            (from p in productsTable
             select new {Id=p.Id,p.price}).AsEnumerable()
            .Select(p => new {p.Id, Tax=myfunctions.calculateTax(p.price)});

The AsEnumerable() breaks "composition" - i.e. it stops LINQ-to-SQL from trying to understand calculateTax in terms of TSQL; only the Id and price are retrieved from SQL; then as it processes each row it applies the second projection to calculate the tax.


Are you trying to call a local function, or one in the database? If it's a local function and it's the last thing you're doing, it's easy - you just need a call to AsEnumerable() to force the remainder of the query to execute locally:

var products = productsTable.AsEnumerable()
                            .Select(p => new Product
                                    { p.Id, Tax = CalculateTax(p.Price) });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜