简体   繁体   English

EntityFramework Core 2默认值

[英]EntityFramework Core 2 Default Values

I'm trying to use default values on a couple of my EF models and I'm noticing that either I'm misunderstanding the HasDefaultValue behaviour or its not working as it should. 我正在尝试在几个EF模型上使用默认值,并且注意到我误解了HasDefaultValue行为或它无法正常工作。

I have the following table and backing model 我有下表和支持模型

CREATE TABLE [dbo].[packages]
(
   [Scnumber] BIGINT NOT NULL, 
   [PU] INT NOT NULL,
   [State] SMALLINT NOT NULL DEFAULT 0, 
   [Status] [smallint] NOT NULL, 
   [Created] DATETIME NOT NULL DEFAULT GETDATE(), 
   CONSTRAINT [PK_packages] PRIMARY KEY CLUSTERED ([Scnumber] ASC) ON [PRIMARY], 
)

[Table("packages", Schema = "dbo")]
public class Package
{
   [Key]
   [Column(TypeName = "bigint")]
   public long Scnumber { get; set; }

   [Column]
   [Required]
   public int PU { get; set; }

   [Column(TypeName = "smallint")]
   [Required]
   public PackageStatus Status { get; set; }

   [Column(TypeName = "tinyint")]
   public RecordState State { get; set; }

   [Column]
   public DateTime? Created { get; set; }    
}

In order to apply default values I've also got the following in my OnModelCreating() 为了应用默认值,我还在OnModelCreating()了以下内容

modelBuilder.Entity<Package>(entity =>
{
   entity.Property(r => r.State)
      .HasDefaultValue(RecordState.Active);

   entity.Property(r => r.Created)
      .HasDefaultValue(DateTime.Now);
});

When I attempt to save a new object I get the following exception: 当我尝试保存新对象时,出现以下异常:

SqlException: Cannot insert the value NULL into column 'State', table 'app.dbo.packages'; SqlException:无法将值NULL插入表“ app.dbo.packages”的“状态”列中; column does not allow nulls. 列不允许为空。 INSERT fails. INSERT失败。

This is confusing as if I inspect the object before I save it, it has a default value, but yet I get this exception. 就像我在保存对象之前检查对象一样,它具有默认值,但是却出现此异常,这令人困惑。 I understand the easiest solution would be to simply make sure I set the value of state when I create the object, but this sort of defeats the purpose of HasDefaultValue . 我知道最简单的解决方案是仅在创建对象时确保设置状态值,但这HasDefaultValue的目的。

-- edit -- -编辑-

When I try to add a new object I do the following 当我尝试添加新对象时,请执行以下操作

var package = new Package { Scnumber = 0123456718, PU = 1001 };

_context.Packages.Add(region);
_context.SaveChanges();

Nothing about this is out of the norm but fails, but if I run the following it works 一切都没有超出正常范围,但失败了,但是如果我运行以下命令,它将起作用

var package = new Package {Scnumber = 0123456718, PU = 1001, Status = PackageStatus.Rejected, State = RecordState.Staging, Created = DateTime.Now };

_context.Packages.Add(region);
_context.SaveChanges();

public enum PackageStatus : short
{
   New,
   PendingValidation,
   CheckedOut,
   Approved,
   Rejected,
   PendingRender,
   Rendered,
   RenderFailed,
   PendingPrint,
   Printed,
   PrintFailed,
   Cancelled,
   PendingDownload,
   Downloaded,
   DownloadError,
   SystemUpdated, 
}

public enum RecordState : byte
{
    Active,
    Deleted,
    Staging,
}

I have a .HasDefaultValueSql("((0))") working in my current project. 我的当前项目中有一个.HasDefaultValueSql("((0))")

Also found .HasDefaultValueSql("getdate()") and .HasDefaultValue(3); 还发现了.HasDefaultValueSql("getdate()").HasDefaultValue(3); here . 在这里

I encountered the same issue. 我遇到了同样的问题。 After updates in OnModelCreating you have to apply migration to database. OnModelCreating进行更新后,您必须将迁移应用于数据库。 Write dotnet ef migrations add defaultValuesAddedToPackage and then dotnet ef database update . 编写dotnet ef migrations add defaultValuesAddedToPackage ,然后dotnet ef database update This makes default value on column type so you don't need to explicitely set in your new entity or in sql insert. 这使列类型成为默认值,因此您无需在新实体或sql插入中显式设置。 If you write dotnet ef migrations script you see code something like ALTER TABLE [packages] ADD DEFAULT 0 FOR [State]; 如果编写dotnet ef migrations script则会看到类似ALTER TABLE [packages] ADD DEFAULT 0 FOR [State];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM