简体   繁体   English

如何将SQL Server日期转换为C#DateTime

[英]How to convert SQL Server date into C# DateTime

I'm calling a stored procedure (using SQL Server 2012) in my C# app and converting the results into ac# object. 我正在C#应用程序中调用存储过程(使用SQL Server 2012),并将结果转换为ac#对象。 The object has a datetime property, and the stored procedure returns a date as one of its columns. 该对象具有datetime属性,并且存储过程返回日期作为其列之一。 The object datetime property is always 01/01/0001 00:00:00 when parsing the query result. 解析查询结果时,对象的datetime属性始终为01/01/0001 00:00:00

Here's my code to consume the stored procedure, the object used to parse the results, and the actual stored procedure itself 这是我使用存储过程的代码,用于解析结果的对象以及实际存储过程本身的代码

public IEnumerable<InvoicingReportDto> GetInvoivingReportPerUser(DateTime startdate, DateTime enddate)
{
    string sproc = "[Updater].[InvoicingReportPerUser] @STARTDATE, @ENDDATE";

    var result = dbContext.Database.SqlQuery<InvoicingReportDto>
        (
            sproc,
            new SqlParameter("@STARTDATE", startdate.Date),
            new SqlParameter("@ENDDATE", enddate.Date)
        );

    return result.ToList();
}

public class InvoicingReportDto
{
    public DateTime LastUpdate { get; set; }
    public string UpdatedBy { get; set; }
    // other properties omitted
}

SQL Server stored procedure: SQL Server存储过程:

CREATE PROCEDURE [Updater].[InvoicingReportPerUser]
    @STARTDATE DATETIME,
    @ENDATE DATETIME
AS
BEGIN
    SELECT 
        CAST(LastUpdate as DATE) AS LastUpdateDate,
        UpdatedBy,
        SUM(CASE WHEN CompanyStatusID = 1 THEN 1 ELSE 0 END) AS [NoStatus],
        SUM(CASE WHEN CompanyStatusID = 2 THEN 1 ELSE 0 END) AS Complete,
        SUM(CASE WHEN CompanyStatusID = 3 THEN 1 ELSE 0 END) AS [CeasedTrading],
        SUM(CASE WHEN CompanyStatusID = 4 THEN 1 ELSE 0 END) AS [NoInterested],
        SUM(CASE WHEN CompanyStatusID = 5 THEN 1 ELSE 0 END) AS [Wrongnumber],
        SUM(CASE WHEN CompanyStatusID = 6 THEN 1 ELSE 0 END) AS [FirstCall],
        SUM(CASE WHEN CompanyStatusID = 7 THEN 1 ELSE 0 END) AS [SecondCall],
        SUM(CASE WHEN CompanyStatusID = 8 THEN 1 ELSE 0 END) AS [ThirdCall],
        SUM(CASE WHEN CompanyStatusID = 9 THEN 1 ELSE 0 END) AS [Research],
        SUM(CASE WHEN CompanyStatusID = 10 THEN 1 ELSE 0 END) AS [EmailRequired],
        SUM(CASE WHEN CompanyStatusID = 11 THEN 1 ELSE 0 END) AS [Liquidation],
        SUM(CASE WHEN CompanyStatusID = 12 THEN 1 ELSE 0 END) AS [Receivership],
        SUM(CASE WHEN CompanyStatusID = 13 THEN 1 ELSE 0 END) AS [NotListed]
    FROM 
        Table
    JOIN 
        Updater.CompanyStatus CS ON CS.ID = CompanyStatusID
    WHERE 
        LastUpdate BETWEEN CAST(@STARTDATE AS DATE) AND CAST(@ENDATE AS DATE)
    GROUP BY 
        CAST(LastUpdate as DATE), UpdatedBy
    ORDER BY 
        CAST(LastUpdate as DATE)
END

I would expect my Dto object to have its LastUpdate property set to reflect the date returned from the stored procedure, but it's always 01/01/0001 我希望Dto对象的LastUpdate属性设置为反映存储过程返回的日期,但始终为01/01/0001

According to the documentation your entity attribute names need to match the name of the columns. 根据文档,您的实体属性名称需要与列名称匹配。 Yours don't appear to (LastUpdate vs LastUpdateDate). 您的似乎没有(LastUpdate与LastUpdateDate)。 You need to either change the name of your property: 您需要更改媒体资源的名称:

public class InvoicingReportDto
{
    public DateTime LastUpdateDate { get; set; }
    public string UpdatedBy { get; set; }
    // other properties omitted
}

or change the column alias 或更改列别名

CAST(LastUpdate as DATE) as LastUpdate,

Your code looks correct except you did not run your stored procedure. 您的代码看起来正确,除非您没有运行存储过程。 You should write EXEC to run your stored procedure: 您应该编写EXEC来运行您的存储过程:

string sproc = "EXEC [Updater].[InvoicingReportPerUser] @STARTDATE, @ENDDATE";

And double check what returns the following code at SQL Server Management Studio: 然后在SQL Server Management Studio中仔细检查是什么返回了以下代码:

DECLARE @STARTDATE date = '2018-12-19', @ENDDATE date = '2018-12-11'
exec [Updater].[InvoicingReportPerUser] @STARTDATE, @ENDDATE

In addition, change your property LastUpdate of InvoicingReportDto to: 此外,将InvoicingReportDto的属性LastUpdate更改为:

public DateTime LastUpdateDate { get; set; }

IMO, it isn't necessary to create procedure to just run your query. IMO,没有必要创建仅运行查询的过程。 You could define your query in some string variable in code, so you have everything centrlized in your code and use it together with SqlConnection , SqlCommand and SqlDatareader : 您可以在代码中的某些字符串变量中定义查询,因此您可以将所有内容集中在代码中,并将其与SqlConnectionSqlCommandSqlDatareader结合使用:

using(SqlConnection conn = new SqlConnection(/* args */))
{
    using(SqlCommand com = new SqlCommand())
    {
        com.Connection = conn;
        com.CommandText = /*your query goes here */ ;
        conn.Open();
        using(SqlDataReader reader = com.ExecuteReader())
        {
            // read your result here and manipulate them
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM