无法读取数据库中的值

时间:2019-05-06 21:56:48

标签: c# vb.net entity-framework

使用EntityFramework 6.2.0

我的模型如下:

<Table("Invoice_Totals")>
Public Class Invoice

    <Key>
    <Column("Invoice_Number")>
    Public Property IntegrationKey As Int64

    <Column("CustNum")>
    Public Property CustomerKey As String = String.Empty

    <Column("DateTime")>
    Public ReadOnly Property CreatedTime As DateTime


    <Column("Grand_Total")>
    Public Property Price As Decimal = Decimal.MaxValue

    <Column("Amt_Tendered")>
    Public Property Payment As Decimal = 0

    <Column("Amt_Change")>
    Public Property PaymentChange As Decimal = 0

End Class

此查询:

Using database As PosModels.PosDatabase = PosModels.PosDatabase.CreateWithNoProxies
    Dim q As IQueryable(Of PosModels.Invoice) = database.Invoices
    posInvoices = q.ToList
End Using

产生此SQL:

SELECT 
    [Extent1].[Invoice_Number] AS [Invoice_Number], 
    [Extent1].[CustNum] AS [CustNum], 
    [Extent1].[Grand_Total] AS [Grand_Total], 
    [Extent1].[Amt_Tendered] AS [Amt_Tendered], 
    [Extent1].[Amt_Change] AS [Amt_Change]
    FROM [dbo].[Invoice_Totals] AS [Extent1]

如您所见,查询中不包括列[DateTime]。我认为是因为“ DateTime”是一种SQL关键字/数据类型。有什么方法可以让EF正确执行此查询?

即使在“手动”执行查询时,对象映射器也似乎没有插入:

posInvoices = database.Database.SqlQuery(Of PosModels.Invoice)($"
                SELECT 
                    [Extent1].[Invoice_Number] AS [IntegrationKey], 
                    [Extent1].[CustNum] AS [CustomerKey], 
                    [Extent1].[DateTime] AS [CreatedTime],
                    [Extent1].[Grand_Total] AS [Price], 
                    [Extent1].[Amt_Tendered] AS [Payment], 
                    [Extent1].[Amt_Change] AS [PaymentChange]
                    FROM [dbo].[Invoice_Totals] AS [Extent1]
            ").ToList

这仍然没有填写CreatedTime属性的任何值。与上一个查询一样,模型中的所有值都保留在DateTime.MinValue。数据库中最古老的数据是2011年的数据。

1 个答案:

答案 0 :(得分:1)

您已将其声明为ReadOnly属性

 Public ReadOnly Property CreatedTime As DateTime

这意味着只有构造函数可以设置它。 EF Core支持Backing Fields,可用于实现只读属性。但是在EF6中,必须映射到数据库列的所有属性。