如何避免linq中的视图子查询

时间:2012-11-13 19:57:59

标签: c# .net linq linq-to-entities

我正在使用linq从表和视图类中检索MVC 4中的数据。 如果我使用linq从视图中提取数据,如下所示:

db.vwContractMVC.Where(x => x.NID == id && x.Date >= pin && x.Date <= pen).ToList();

然后linq使用子查询构造sql查询,如下所示:

SELECT 
[Extent1].[NID] AS [NID], 
[Extent1].[Date] AS [Date], 
[Extent1].[Column1] AS [Column1], 
[Extent1].[Column2] AS [Column2], 
[Extent1].[Column3] AS [Column3]
FROM (SELECT 
      [vwContractMVC].[NID] AS [NID], 
      [vwContractMVC].[Date] AS [Date], 
      [vwContractMVC].[Column1] AS [Column1], 
      [vwContractMVC].[Column2] AS [Column2], 
      [vwContractMVC].[Column3] AS [Column3]
      FROM [dbo].[vwContractMVC] AS [vwContractMVC]) AS [Extent1]
WHERE ([Extent1].[NID] = @p__linq__0) AND ([Extent1].[Date] >= @p__linq__1) AND ([Extent1].[Date] <= @p__linq__2)

如果使用表格 - 查询很简单:

SELECT 
[Extent1].[NID] AS [NID], 
[Extent1].[Date] AS [Date], 
[Extent1].[Column1] AS [Column1], 
[Extent1].[Column2] AS [Column2], 
[Extent1].[Column3] AS [Column3]
FROM [dbo].[Contract] AS [Extent1]
WHERE ([Extent1].[NID] = @p__linq__0) AND ([Extent1].[Date] >= @p__linq__1) AND ([Extent1].[Date] <= @p__linq__2)

问题是 - 如何让linq从视图中进行简单的选择,当然,如果可能的话)

我可以为此创建存储过程,但我希望使用现有的表和视图。

1 个答案:

答案 0 :(得分:1)

使用子查询创建实际的SQL,因为您正在从视图中进行选择。如果您不是多次从同一视图中选择,只需从实际表中创建linq查询,否则您可以创建一个返回视图sql AsQueryable()并根据需要添加where子句的方法。

代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace LinqToView
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var context = new NWEntities())
                {
                    ViewQuery(context).Where(vw => vw.Product == "Foo").ToList();
                }
            }

            private static IQueryable<vwProducts_by_Categories> ViewQuery(NWEntities context)
            {
                return
                    from p in context.Products
                    join c in context.Categories on p.CategoryID equals c.CategoryID
                    select new vwProducts_by_Categories { Product = p.ProductName, Category = c.CategoryName };
            }
        }

        public class vwProducts_by_Categories
        {
            public string Product { get; set; }
            public string Category { get; set; }
        }
    }

生成:

    SELECT 
    [Extent2].[CategoryID] AS [CategoryID], 
    [Extent1].[ProductName] AS [ProductName], 
    [Extent2].[CategoryName] AS [CategoryName]
    FROM  [dbo].[Products] AS [Extent1]
    INNER JOIN [dbo].[Categories] AS [Extent2] ON [Extent1].[CategoryID] = [Extent2].[CategoryID]
    WHERE N'Foo' = [Extent1].[ProductName]