Mapping a DateTimeOffset entity map for SQL Server DateTime

Is there a way to map a property DateTimeOffsetto a SQL Server column datetimewith the assumption that you cannot change either side, which means that the property and column must remain these date types?

I know that the easiest way is to make them match, but want to know if there is a way around this. I was looking for custom mappings, but it seemed to me that I needed to map all the columns, not just the property DateTimeOffset.

I tried:

modelBuilder.Entity<Customer>().Property(c => c.LastModifiedOn).HasColumnType("datetime");

But it caused an error Member Mapping specified is not valid.

I was hoping I could put the value of the property UtcDateTime DateTimeOffsetin db, and when the reading will have a value DateTimeOffsetin UTC (i.e. it has a zero offset).

Thank.

+5
1

. DateTimeOffset .NET- DateTimeOffset SQL. , EF / . DateTime, .

Customer , , @cincura.net :

public class Customer
{
    public static class CustomerExpressions
    {
        public static readonly Expression<Func<Customer, DateTime>> LastModifiedOn = c => c.LastModifiedOnInternal;
    }

    // Other properties

    public DateTimeOffset LastModifiedOn
    {
        get { return new DateTimeOffset(LastModifiedOnInternal); }
        set { LastModifiedOnInternal = value.DateTime; }
    }

    private DateTime LastModifiedOnInternal { get; set; }
}

: DataTime, , - DateTimeOffset . :

public class Context : DbContext
{
    public DbSet<Customer> Customers { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(c => c.LastModifiedOn);
        modelBuilder.Entity<Customer>().Property(Customer.CustomerExpressions.LastModifiedOn).HasColumnName("LastModifiedOn");
    }
}

, DateTime UTC?

+12

All Articles