1

我正在使用 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 从视图中进行简单的选择)

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

4

1 回答 1

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]
于 2012-11-13T22:17:48.187 回答