【问题标题】:Code First default DateTime not working代码优先默认日期时间不起作用
【发布时间】:2012-11-18 11:59:42
【问题描述】:

我有一个 DateTime 字段,只要将记录输入到该表中,我就想将其设置为默认值(它基本上是一个 DateCreated 字段)。这是我的代码

public partial class User
    {
        public User()
        {
            this.DateCreated = DateTime.Now; //set default value
            Roles = new HashSet<Role>();
        }

        public ICollection<Role> Roles { get; set; } //many to many relationship

        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string Surname { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string City { get; set; }

        //foreign key
        public int CountryId { get; set; }
        //navigation properties
        public virtual Country Country { get; set; }

        //foreign key
        public int LanguageId { get; set; }
        //navigation properties
        public virtual Language Language { get; set; }

        public string EmailAddress { get; set; }
        public long FacebookId { get; set; }
        public DateTime DateCreated { get; set; }
    } }

    public class UserConfiguration : EntityTypeConfiguration<User>
    {
        public UserConfiguration()
        {
            ToTable("Users", schemaName: "Main");

            HasKey(s => s.UserId);

            Property(p => p.FirstName)
                .IsRequired().HasMaxLength(50); //translates to non-nullable     

            Property(p => p.Surname)
                .IsRequired().HasMaxLength(50);

            Property(p => p.Username)
                .IsRequired().HasMaxLength(20);

            Property(p => p.Password)
                .IsRequired().HasMaxLength(20);

            Property(p => p.City)
                .IsOptional().HasMaxLength(50); //not required

            Property(p => p.LanguageId)
                .IsRequired();

            Property(p => p.EmailAddress)
                .IsRequired().HasMaxLength(50);

            Property(p => p.FacebookId)
                .IsOptional();

            Property(p => p.DateCreated) 
                .IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            //attribute ensures that DateCreated only gets saved to the database when you are adding a 
            //row, not when you are saving
        }
    }

    context.Users.Add(new User
                {
                    FirstName = "Test",
                    Surname = "User",
                    Username = "testuser72",
                    Password = "testuser72",
                    City = "London",
                    CountryId = context.Countries.Single(d => d.CountryName == "United Kingdom").CountryId,
                    LanguageId = context.Languages.Single(d => d.LanguageName == "English").LanguageId,
                    EmailAddress = "testuser@yahoo.co.uk",
                    Roles = new Role[] { context.Roles.Single(r => r.RoleName == "Content Editor"), context.Roles.Single(s => s.RoleName == "User") }
                });

为什么当我尝试使用上面的代码添加用户时,为什么会出现错误“无法将值 NULL 插入列 'DateCreated',表 'Main.Users'; 列不允许空值。插入失败。'?

【问题讨论】:

    标签: c# entity-framework code-first


    【解决方案1】:

    使用“HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)”选项,您说您希望它是一个自动递增的列。这不是你想要的。您想要 Computed,它表示该值由数据库自动填充,而不是由您填充。

    仅更改此选项并不能解决您的问题。通过将其设置为 Computed,您说您不希望它采用您自己的值,因此在构造函数中设置它是没有意义的。您必须将数据库级别的默认值设置为“GETDATE()”。使用迁移时,将字符串添加到 defaultValueSql 参数中。

    【讨论】:

    • 所以在最初的数据库创建和播种中,我将这些日期时间字段排除在外,然后在使用迁移时添加它们?
    • 不,当您通过普通 SQL 创建数据库时,请执行以下操作:“添加 CreatedDate datetime2 default GETDATE()”。当您使用迁移创建表时,您修改迁移并为您的列传递“defaultValueSql”参数。
    【解决方案2】:

    通过运行Add-Migration 20170303_example 生成迁移后,转到20170303_example 文件,然后

    以查找日期时间列为例:

    CreatedDate = c.DateTime(nullable: false)
    

    并将其更新为:

    CreatedDate = c.DateTime(defaultValueSql: "GETDATE()") 
    

    最后在您的包管理器控制台中运行Update-Database 命令来更新数据库。

    【讨论】:

      猜你喜欢
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 2019-12-14
      • 1970-01-01
      • 2018-04-28
      相关资源
      最近更新 更多