Can SQL level functions be made available to LINQ to Entity queries?

前端 未结 2 1269
Happy的楠姐
Happy的楠姐 2021-01-23 03:07

I wish I could write LINQ to Entity queries that called other functions:

from c in context.Widgets
where MyFunc(c.name)
select c

That causes an

2条回答
  •  忘掉有多难
    2021-01-23 03:49

    EF is pitched at synchronising .net classes with the structure of the database and is best where the database is dumb and all the logic sits in the classes.

    But you can map to functions and stored procedures - it's a bit technical to explain (a lot easier to do) - let me find some links for you.

    Here's a bad way to do it:

    // Query that calls the OrderTotal function to recalculate the order total.
    string queryString = @"USING Microsoft.Samples.Entity;
        FUNCTION OrderTotal(o SalesOrderHeader) AS
        (o.SubTotal + o.TaxAmt + o.Freight)
    
        SELECT [order].TotalDue AS currentTotal, OrderTotal([order]) AS calculated
        FROM AdventureWorksEntities.SalesOrderHeaders AS [order]
        WHERE [order].Contact.ContactID = @customer";
    
    int customerId = 364;
    
    
    using (AdventureWorksEntities context =
        new AdventureWorksEntities())
    {
        ObjectQuery query = new ObjectQuery(queryString, context);
        query.Parameters.Add(new ObjectParameter("customer",customerId));
    
        foreach (DbDataRecord rec in query)
        {
            Console.WriteLine("Order Total: Current - {0}, Calculated - {1}.", 
                rec[0], rec[1]);
        }
    }
    

    http://msdn.microsoft.com/en-us/library/dd490951.aspx

    An here's how to do it properly:

    http://scipbe.wordpress.com/2010/08/30/stored-procedures-udfs-in-the-entity-framework-part-1/

提交回复
热议问题