How to add day to date in Linq to SQL

前端 未结 10 1095
栀梦
栀梦 2020-12-16 13:53

I am writing this code. Here dt is input into the function, as well as someint. The column Exp is a T-SQL date column, which comes as a DateTime through Linq.



        
相关标签:
10条回答
  • 2020-12-16 14:37

    I solve my problem with that query.

    return (from a in dataContext.TableOfA
           where a.name == "Test" &&
           DbFunctions.AddHours(DbFunctions.CreateDateTime(
     a.Exp.Value.Year,a.Exp.Value.Month,a.Exp.Value.Day,a.Exp.Value.Hour,a.Exp.Value.Minute,
    a.Exp.Value.Millisecond),Someint) >=     
    DbFunctions.CreateDateTimeOffset(dt.Year,dt.Month,dt.Day,dt.Hour,dt.Minute,dt.Millisecond,0)
           select a).First();
    
    0 讨论(0)
  • 2020-12-16 14:38

    Have you considered writing your own user-defined function that basically takes in an int (for number of days) and date, returns the results of a dateadd()? Then pull that into the LINQ class in your project. Then, instead of calling .AddDate(), call your UDF - this will allow you to keep everything in your LINQ query without having to manually piece together a SQLCommand.

    0 讨论(0)
  • 2020-12-16 14:42

    Create a new DateTime object and use AddDays method after that:

    new DateTime(t.Key.Year,t.Key.Month,T.Key.Day).AddDays(xx)
    
    0 讨论(0)
  • 2020-12-16 14:43

    It seems like this scenario is mostly fixed in .NET 4.5.

    However, if you write:

    var activeProducts = from p in db.Products where DateTime.Now() <= p.EndDate.Date.AddDays(7) select p;
    

    You will get the same error message as described in the OP.

    But, if you write:

    var activeProducts = from p in db.Products where DateTime.Now() <= p.EndDate.AddDays(7) select p;
    

    Then you can enter the land of milk and honey. Note that I did not call .Date on the database's DateTime representation. This seems to be an edge case missing test coverage by the LINQ 2 SQL framework in 4.5

    0 讨论(0)
提交回复
热议问题