系统使用有效SQL完成查询后,EntityFramework中出现InvalidOperationException
本文关键字:EntityFramework InvalidOperationException 查询 有效 SQL 系统 | 更新日期: 2023-09-27 18:25:20
我已经搜索了几天这个问题的答案,但我完全被卡住了。我认为这只是我没有寻找正确的东西,因为我确信解决方案很简单,只是我做错了什么。
出于某种原因,当我尝试使用下面的代码这样的实体框架从数据库中获取数据时,什么都没有发生。当我遍历代码时,我发现它已经到达了从数据库获取数据的行,然后就跳出了函数,没有错误,什么都没有,应用程序只是继续运行,但我没有获取数据。
private void CreateKitWindow_Loaded(object sender, RoutedEventArgs e)
{
string kitID = "";
using (MyContext foo = new MyContext())
{
foo.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
LaminationKit theKit = foo.Lamination_Kit.OrderByDescending(x => x.KitNumber).First();
kitID = theKit.KitNumber;
}
kitNumber.Content = kitID;
}
我在Stack Overflow上发现了数据库日志行,并添加了它并检查了结果。
Opened connection at 2/12/2015 2:26:22 p.m. +13:00
SELECT TOP (1)
[Extent1].[UID] AS [UID],
[Extent1].[KitNumber] AS [KitNumber],
[Extent1].[dateCreated] AS [dateCreated],
[Extent1].[lastTransaction] AS [lastTransaction],
[Extent1].[daysLeft] AS [daysLeft],
[Extent1].[hoursLeft] AS [hoursLeft],
[Extent1].[minsLeft] AS [minsLeft],
[Extent1].[jobNo] AS [jobNo],
[Extent1].[assemblyNo] AS [assemblyNo],
[Extent1].[storageLocation] AS [storageLocation],
[Extent1].[jobName] AS [jobName],
[Extent1].[jobDescription] AS [jobDescription],
[Extent1].[mouldNumber] AS [mouldNumber],
[Extent1].[targetJob] AS [targetJob],
[Extent1].[targetAssembly] AS [targetAssembly],
[Extent1].[targetLine] AS [targetLine],
[Extent1].[dateFrozen] AS [dateFrozen],
[Extent1].[dateThawed] AS [dateThawed],
[Extent1].[cookDate] AS [cookDate]
FROM [dbo].[LaminationKit] AS [Extent1]
ORDER BY [Extent1].[KitNumber] DESC
-- Executing at 2/12/2015 2:26:22 p.m. +13:00
-- Completed in 5 ms with result: SqlDataReader
Exception thrown: 'System.InvalidOperationException' in EntityFramework.dll
Closed connection at 2/12/2015 2:26:22 p.m. +13:00
有人能告诉我这里发生了什么吗?查询是有效的,并且根据此查询成功完成,但随后抛出异常。我把那个精确的查询粘贴到SQL server management studio中,它运行良好,完全符合我的要求。
以下是上下文,如果这有助于(去除额外的东西)
class MyContext : DbContext
{
public MyContext() : base("Password=xxxxxxx;Persist Security Info=True;User ID=xxxxxxxx;Data Source=ssnzsql02;Packet Size=4096;Initial Catalog=SS_Outlife_E10")
{
}
public DbSet<LaminationKit> Lamination_Kit { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
另一件事是,我可以使用更长的获取数据
var foo = from item in context.table
where item.this == something
Orderby item.that
select item
foreach(var t in foo)
{
//loop through and do stuff
}
方法很好,但我不想在任何情况下都这样做。这个问题不仅仅发生在这个表上,它发生在数据库中的许多不同的表上。
谢谢cFrozenDeath和FizzBuzz,我不知道为什么我一开始就不想尝试这个。(可能是因为在运行期间没有发生实际的崩溃或中断)
我试着抓住它,看看它是否能抓住它,我收到了的消息
The 'dateFrozen' property on 'LaminationKit' could not be set to a 'null' value. You must set this property to a non-null value of type 'System.DateTime'.
事实证明,是超级简单的,我刚刚降级了,我需要确保我将允许空值的表字段的数据类型设置为可空#EpicFacepalm
更改
public DateTime dateFrozen { get; set; }
to
public Nullable<DateTime> dateFrozen { get; set; }
现在要检查所有事情并修复所有其他问题。