Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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()

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'; column does not allow nulls. INSERT fails.

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.

-- 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,
}
like image 819
Marqueone Avatar asked Jan 26 '18 11:01

Marqueone


People also ask

How do I change the default value for EF core?

In EF core released 27th June 2016 you can use fluent API for setting default value. Go to ApplicationDbContext class, find/create the method name OnModelCreating and add the following fluent API. – Daniel Z.

Should I use EF6 or EF core?

Keep using EF6 if the data access code is stable and not likely to evolve or need new features. Port to EF Core if the data access code is evolving or if the app needs new features only available in EF Core. Porting to EF Core is also often done for performance.

Can you use EF6 in .NET core?

You can't put an EF6 context in an ASP.NET Core project because . NET Core projects don't support all of the functionality that EF6 commands such as Enable-Migrations require.

Is EF core fast?

EF Core 6.0 performance is now 70% faster on the industry-standard TechEmpower Fortunes benchmark, compared to 5.0. This is the full-stack perf improvement, including improvements in the benchmark code, the . NET runtime, etc. EF Core 6.0 itself is 31% faster executing queries.


1 Answers

I have a .HasDefaultValueSql("((0))") working in my current project.

Also found .HasDefaultValueSql("getdate()") and .HasDefaultValue(3); here.

like image 95
Matheus Lacerda Avatar answered Sep 27 '22 16:09

Matheus Lacerda