C# 代码第一个默认日期时间不工作

C# 代码第一个默认日期时间不工作,c#,entity-framework,code-first,C#,Entity Framework,Code First,我有一个DateTime字段,每当将记录输入到该表中时,我都希望将其设置为默认值(它基本上是一个DateCreated字段)。这是我的密码 public partial class User { public User() { this.DateCreated = DateTime.Now; //set default value Roles = new HashSet<Role>();

我有一个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") }
                });
公共部分类用户
{
公共用户()
{
this.DateCreated=DateTime.Now;//设置默认值
Roles=newhashset();
}
公共ICollection角色{get;set;}//多对多关系
public int UserId{get;set;}
公共字符串名{get;set;}
公共字符串姓氏{get;set;}
公共字符串用户名{get;set;}
公共字符串密码{get;set;}
公共字符串City{get;set;}
//外键
public int CountryId{get;set;}
//导航属性
公共虚拟国家{get;set;}
//外键
public int LanguageId{get;set;}
//导航属性
公共虚拟语言{get;set;}
公共字符串电子邮件地址{get;set;}
公共长FacebookId{get;set;}
public DateTime DateCreated{get;set;}
} }
公共类UserConfiguration:EntityTypeConfiguration
{
公共用户配置()
{
ToTable(“用户”,schemaName:“主”);
HasKey(s=>s.UserId);
属性(p=>p.FirstName)
.IsRequired().HasMaxLength(50);//转换为不可为空
属性(p=>p.姓氏)
.IsRequired().HasMaxLength(50);
属性(p=>p.Username)
.IsRequired().HasMaxLength(20);
属性(p=>p.Password)
.IsRequired().HasMaxLength(20);
地产(p=>p.City)
.IsOptional().HasMaxLength(50);//不需要
属性(p=>p.LanguageId)
.IsRequired();
属性(p=>p.EmailAddress)
.IsRequired().HasMaxLength(50);
属性(p=>p.FacebookId)
.等民族();
属性(p=>p.DateCreated)
.IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//属性确保DateCreated仅在添加时保存到数据库中
//行,而不是在保存时
}
}
context.Users.Add(新用户
{
FirstName=“Test”,
姓氏=“用户”,
Username=“testuser72”,
Password=“testuser72”,
City=“伦敦”,
CountryId=context.Countries.Single(d=>d.CountryName==“英国”).CountryId,
LanguageId=context.Languages.Single(d=>d.LanguageName==“English”).LanguageId,
电子邮件地址=”testuser@yahoo.co.uk",
Roles=newrole[]{context.Roles.Single(r=>r.RoleName==“内容编辑器”),context.Roles.Single(s=>s.RoleName==“用户”)}
});
为什么当我尝试使用上面的代码添加用户时,为什么会出现错误“无法将NULL值插入列“DateCreated”,表“Main.Users”; 列不允许空值。插入失败。“?

如果选择“HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)”,则表示希望它是一个自动递增的列。这不是你想要的。您需要计算,这表示该值由数据库自动填充,而不是由您填充


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

一旦通过运行
添加迁移20170303_示例
生成迁移,请转到
20170303_示例
文件,然后

查找DateTime列,例如:

CreatedDate = c.DateTime(nullable: false)
并将其更新为:

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

最后在PackageManager控制台中运行
updatedatabase
命令来更新数据库

因此,在最初的数据库创建和种子设定中,我保留了这些日期时间字段,然后在以后使用迁移时添加它们?不,当您使用纯SQL创建数据库时,请执行以下操作:“添加CreatedDate datetime2 default GETDATE()”。使用迁移创建表时,修改迁移并为列传递“defaultValueSql”参数。