LINQ实体框架4.2 datetime比较失败 [英] LINQ Entity Framework 4.2 datetime comparison fails

查看:151
本文介绍了LINQ实体框架4.2 datetime比较失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跟随我描述了一个使用EF 4.2和LINQ的问题。我已经在多个系统上尝试了这一点,并且在64位和32位二进制文​​件中使用了多种风格的SQL(SQL Express和SQL 2008 R2 Sp1),VS 2010 Pro和Premium,无论是使用调试器还是尝试直接运行二进制。我想知道我是否偶然发现,如果这是EF的问题,或者更有可能是我的代码出现问题,而且我错过了与LINQ或EF相关的细微差别。任何帮助将不胜感激,一直在6个小时,我的Google JuJu不够强大我害怕。



我有一个简单的模型命名会话组成ID(Guid),Name(String)和Timestamp(DateTime)。我可以添加会话到dbcontext,并在调试中验证了会话记录确实存储在数据库中。用于创建会话对象的时间戳记存储在本地变量中,并且在存储之后立即尝试将会话检索到会话对象的新实例中。检索会话(LINQ)的代码抛出System.InvalidOperationException序列不包含以下堆栈跟踪的元素

 在System.Linq.Enumerable.First [TSource](IEnumerable`1源)
在System.Data.Objects.ELinq.ObjectQueryProvider。< GetElementFunction> b__0 [TResult](IEnumerable`1序列)
在System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle [TResult](IEnumerable`1查询,表达式queryRoot)
在System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute [S](表达式表达式)
在System.Data.Entity.Internal.Linq.DbQueryProvider.Execute [TResult](表达式表达式)
在System.Linq.Queryable.First [TSource](IQueryable`1源)
at efwtf.Program.Main(String [] args)in d:\vs2010\efwtf\efwtf\Program.cs:line 19
在System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,String [] args)
在System.AppDomain.ExecuteAssembly(String asse mblyFile,Evidence assemblySecurity,String [] args)
在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
在System.Threading.ThreadHelper.ThreadStart_Context(Object state)
在System.Threading .executionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean ignoreSyncCtx)
在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state)
在System.Threading.ThreadHelper。 ThreadStart()

我可以在调试器中钻取ctx.Sessions,并在结果集中查看我试图检索的会话确实存在,如果我迭代结果集并手动比较两个时间戳,我可以按预期提取会话。如果我运行代码并传递在上一次运行中添加到数据库的记录的时间戳值,它将工作。我可以找到工作,最糟糕的情况下,可能会将数据类型更改为字符串,但是它告诉我这不起作用,我假设这可能是问题的一部分,应该支持该功能。代码如下。

  using System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Data.Entity;
使用System.ComponentModel.DataAnnotations;

命名空间efwtf
{
类程序
{
static void Main(string [] args)
{
上下文ctx = new Context();
DateTime ts = DateTime.UtcNow;
会话s1 = new Session(){Id = Guid.NewGuid(),Name =Testing,TimeStamp = ts};
ctx.Sessions.Add(s1);
ctx.SaveChanges();

会话s2 =(从ctx.Sessions中的s
其中(s.Name ==Testing&& s.TimeStamp.Equals(ts))
select s).First();

Console.WriteLine(s2.Name,s2.TimeStamp);
}
}

类上下文:DbContext
{
public DbSet< Session>会话{get;组; }
}

class Session
{
[Key]
public Guid Id {get;组; }
public string Name {get;组; }
public DateTime TimeStamp {get;组;
}
}

我已经尝试了LINQ语句的变体,包括s.datetime.equals(ts)和datetime.compare(s.datetime,ts)== 0,但每次都抛出相同的异常。



任何人都有想法?那是我吗?这个代码是否使我的二进制文件看起来很大? = ^)



提前感谢

解决方案

为了获得这个工作,我将TimeStamp的数据列修改为数据库中的DateTime2数据类型如下。

  class Session 
{
[Key]
public Guid Id {get;组; }
public string Name {get;组; }

[Column(TypeName =datetime2)]
public DateTime TimeStamp {get;组; }
}

最终认为这是一个工作,因为这个问题似乎是谎言LINQ在某种程度上有助于我摆脱障碍,并且认为我会发布在这里,以防其他人遇到这种情况。


Followind describes an issue I am running into using EF 4.2 and LINQ. I've tried this on multiple systems, and multiple flavors of SQL (SQL Express and SQL 2008 R2 Sp1), VS 2010 Pro and Premium, both in 64 bit and 32 binaries, both with the debugger, and attempting to run the binary directly. I'm wondering what I've stumbled against, if it's an issue with EF, or more likely an issue with my code and I'm missing some nuance either related to LINQ or EF. Any assistance would be greatly appreciated, been at it for 6 hours, my Google JuJu is not strong enough I'm afraid.

I have a simple model named session consisting of an ID (Guid), Name (String), and Timestamp (DateTime). I am able to add a session to the dbcontext, and have verified in debugging that the session record is indeed stored in the database. The timestamp used to create the session object is stored in a local variable, and immediately after storing, I attempt to retrieve the session into a new instance of a session object. The code that retrieves the session (LINQ) throws 'System.InvalidOperationException "Sequence contains no elements"' with the following stacktrace:

at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__0[TResult](IEnumerable`1 sequence)
at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.First[TSource](IQueryable`1 source)
at efwtf.Program.Main(String[] args) in d:\vs2010\efwtf\efwtf\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

I am able to drill into ctx.Sessions in the debugger and see in the resultset that the session that I am trying to retrieve actually does exist, and if I iterate over the result set and manually compare the two timestamps I can extract the session as expected. If I run the code and pass a timestamp value for a record that was added to the database in a previous run, it works. I can find work arounds, worst case, changing the datatype to a string perhaps, but it bugs me that this doesn't work, I'm assuming, which may be part of the problem, that the functionality should be supported. Code follows.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations;

    namespace efwtf
    {
       class Program
       {
          static void Main ( string[] args )
          {
             Context ctx = new Context ();
             DateTime ts = DateTime.UtcNow;
             Session s1 = new Session () { Id = Guid.NewGuid(), Name = "Testing", TimeStamp = ts };
             ctx.Sessions.Add ( s1 );
             ctx.SaveChanges ();

             Session s2 = ( from s in ctx.Sessions
                            where ( s.Name == "Testing" && s.TimeStamp.Equals ( ts ) )
                            select s ).First ();

             Console.WriteLine ( s2.Name, s2.TimeStamp );
          }
       }

       class Context : DbContext
       {
          public DbSet<Session> Sessions { get; set; }
       }

       class Session
       {
          [Key]
          public Guid Id { get; set; }
          public string Name { get; set; }
          public DateTime TimeStamp { get; set; }
       }
    }

I've tried variations on the LINQ statement, including s.datetime.equals(ts) and datetime.compare(s.datetime, ts) == 0 but every time it throws the same exception.

Anyone have any ideas? Is it me? Does this code make my binary look big? =^)

Thanks in advance

解决方案

In order to get this to work, I modified the datacolumn for the TimeStamp to be a DateTime2 datatype in the database as follows.

class Session 
{ 
   [Key] 
   public Guid Id { get; set; } 
   public string Name { get; set; } 

   [Column(TypeName = "datetime2")]
   public DateTime TimeStamp { get; set; } 
} 

Ultimately consider this to be a work around given that the issue appears to lie with LINQ in some way, however it helped me to get past the hurdle and thought I would post here in case anyone else runs into this.

这篇关于LINQ实体框架4.2 datetime比较失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆