gpt4 book ai didi

c# - Code First 默认 DateTime 不工作

转载 作者:行者123 更新时间:2023-11-30 22:23:20 24 4
gpt4 key购买 nike

我有一个 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’;列不允许空值。 INSERT 失败。'?

最佳答案

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

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

关于c# - Code First 默认 DateTime 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13439893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com