Using DateTime properties in Code-First Entity Framework and SQL Server

后端 未结 4 1974
半阙折子戏
半阙折子戏 2020-11-29 03:07

I have an example class book:

public class Book
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public Date         


        
相关标签:
4条回答
  • 2020-11-29 03:19

    You can specify the type in Fluent API:

    modelBuilder.Entity<Book>()
        .Property(f => f.DateTimeAdded)
        .HasColumnType("datetime2");
    

    This creates a datetime2(7) column in the database. If you want to finetune the precision you can use:

    modelBuilder.Entity<Book>()
        .Property(f => f.DateTimeAdded)
        .HasColumnType("datetime2")
        .HasPrecision(0);
    

    ... for a datetime2(0) column in the DB.

    However, the code you have shown in your question works because the datetime type allows to store dates back to around 1750. The exception occurs only for earlier dates. A common reason for this exception is an uninitialized DateTime property because it represents the year 0001 which can't be stored in a datetime column in SQL Server.

    There is no corresponding attribute to define this with data annotations. It's only possible with Fluent API.

    0 讨论(0)
  • 2020-11-29 03:38

    You can annotate the attribute of your class with the type datetime2.

    public class Book
    {
        [Column(TypeName = "datetime2")]
        public DateTime DateAdded { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-29 03:38

    If migrations are enabled you can also adjust stuff right there.

    public override void Up()
    {
        CreateTable(
            "dbo.MyTable",
            c => new
            {
                Date = c.DateTime(false, 7, storeType: "datetime2"),
            });
    }
    
    0 讨论(0)
  • 2020-11-29 03:41

    When saving a date it needs to have a value populated. Thats why you get this error.

    Just use DateTime?. There is no need for the magic above.

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