编写ASP.NET MVC站点时遇到一个奇怪的问题。我在我的SQL Server数据库中有一个视图,它返回一些日期范围。在SSMS中运行查询时,该视图工作正常。
当实体框架模型返回视图数据时,它返回正确的行数,但某些行是重复的。
以下是我所做的一个例子:
SQL Server代码:
已编辑:(表A)
CREATE TABLE [dbo].[A](
[ID] [int] NOT NULL,
[PhID] [int] NULL,
[FromDate] [datetime] NOT NULL,
[ToDate] [datetime] NULL,
CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
( [ID] ASC,
[FromDate] ASC
)) ON [PRIMARY]
CREATE TABLE [dbo].[B](
[PhID] [int] NOT NULL,
[FromDate] [datetime] NULL,
[ToDate] [datetime] NULL,
CONSTRAINT [PK_B] PRIMARY KEY CLUSTERED
( [PhID] ASC )) ON [PRIMARY]
go
CREATE VIEW C as
SELECT A.ID,
CASE WHEN A.PhID IS NULL THEN A.FromDate ELSE B.FromDate END AS FromDate,
CASE WHEN A.PhID IS NULL THEN A.ToDate ELSE B.ToDate END AS ToDate
FROM A
LEFT OUTER JOIN B ON A.PhID = B.PhID
go
INSERT INTO B (PhID, FromDate, ToDate) VALUES (100, '20100615', '20100715')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (1, NULL, '20100101', '20100201')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (1, 100, '20100615', '20100715')
INSERT INTO B (PhID, FromDate, ToDate) VALUES (101, '20101201', '20101231')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (2, NULL, '20100801', '20100901')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (2, 101, '20101201', '20101231')
现在,如果您从C中选择全部,则会获得4个单独的日期范围
在实体框架模型(我称之为'核心')中,添加了视图'C'。
MVC Controller中的:
public class HomeController : Controller
{
public ActionResult Index()
{
CoreEntities db = new CoreEntities();
var clist = from c in db.C
select c;
return View(clist.ToList());
}
}
在MVC视图中:
@model List<RM.Models.C>
@{
foreach (RM.Models.C c in Model)
{
@String.Format("{0:dd-MMM-yyyy}", c.FromDate)
<span>-</span>
@String.Format("{0:dd-MMM-yyyy}", c.ToDate)
<br />
}
}
当我运行所有这些时,它会输出:
01-Jan-2010 - 01-Feb-2010
01-Jan-2010 - 01-Feb-2010
01-Aug-2010 - 01-Sep-2010
01-Aug-2010 - 01-Sep-2010
当它应该这样做时(这是视图返回的内容):
01-Jan-2010 - 01-Feb-2010
15-Jun-2010 - 15-Jul-2010
01-Aug-2010 - 01-Sep-2010
01-Dec-2010 - 31-Dec-2010
另外,我在它上面运行了SQL分析器,根据它,正在执行的查询是:
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[FromDate] AS [FromDate],
[Extent1].[ToDate] AS [ToDate]
FROM (SELECT
[C].[ID] AS [ID],
[C].[FromDate] AS [FromDate],
[C].[ToDate] AS [ToDate]
FROM [dbo].[C] AS [C]) AS [Extent1]
返回正确的数据
因此,实体框架似乎在此期间对数据做了一些事情。
对我而言,一切看起来都很好!我错过了什么吗?
干杯, 本
修改
抱歉,表A应该是:CREATE TABLE [dbo].[A](
[ID] [int] NOT NULL,
[PhID] [int] NULL,
[FromDate] [datetime] NOT NULL,
[ToDate] [datetime] NULL,
CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
( [ID] ASC,
[FromDate] ASC
)) ON [PRIMARY]
答案 0 :(得分:3)
我自己想出来了。
问题在于视图在实体模型中的映射方式。
添加时,它使实体键只是ID。我需要ID和FromDate。所以我在实体键中包含了FromDate,它运行正常。