Making sure that DateTime properties return DateTimeKind.Utc

后端 未结 3 1342
鱼传尺愫
鱼传尺愫 2021-01-01 05:15

Is it possible to define DateTime properties in entity objects that are of Kind == DateTimeKind.Utc by using either the .edmx file, or a t4 template?

W

3条回答
  •  青春惊慌失措
    2021-01-01 05:51

    For our case it was impractical to always specify the DateTimeKind as stated previously:

    DateTime utcDateTime = DateTime.SpecifyKind(databaseDateTime, DateTimeKind.Utc);
    

    If you want to force all DateTime objects coming out of the database to be specified as UTC you'll need to add a T4 transform file and add additional logic for all DateTime and nullable DateTime objects such that they get initialized as DateTimeKind.Utc

    I have a blog post which explains this step by step: http://www.aaroncoleman.net/post/2011/06/16/Forcing-Entity-Framework-to-mark-DateTime-fields-at-UTC.aspx

    In short:

    1) Create the .tt file for your .edmx model

    2) Open the .tt file and find the "WritePrimitiveTypeProperty" method.

    3) Replace the existing setter code. This is everything between the ReportPropertyChanging and the ReportPropertyChanged method callbacks with the following:

    <#+ if( ((PrimitiveType)primitiveProperty.TypeUsage.EdmType).PrimitiveTypeKind == PrimitiveTypeKind.DateTime)
                {
    #>
            if(<#=code.FieldName(primitiveProperty)#> == new DateTime())
            {
                <#=code.FieldName(primitiveProperty)#> = StructuralObject.SetValidValue(value<#=OptionalNullableParameterForSetValidValue(primitiveProperty, code)#>);
    <#+ 
                if(ef.IsNullable(primitiveProperty))
                {  
    #>              
                if(value != null)
                    <#=code.FieldName(primitiveProperty)#> = DateTime.SpecifyKind(<#=code.FieldName(primitiveProperty)#>.Value, DateTimeKind.Utc);
    <#+             } 
                else
                {#>
                <#=code.FieldName(primitiveProperty)#> = DateTime.SpecifyKind(<#=code.FieldName(primitiveProperty)#>, DateTimeKind.Utc);                
    <#+ 
                } 
    #>
            }
            else
            {
                <#=code.FieldName(primitiveProperty)#> = StructuralObject.SetValidValue(value<#=OptionalNullableParameterForSetValidValue(primitiveProperty, code)#>);
            }
    <#+ 
            }
            else
            {
    #>
        <#=code.FieldName(primitiveProperty)#> = StructuralObject.SetValidValue(value<#=OptionalNullableParameterForSetValidValue(primitiveProperty, code)#>);
    <#+ 
            }
    #>
    

提交回复
热议问题