C# Question

EF Core cannot insert the value null into column with default value

I have entity

public class Realtor
public int Id { get; set; }

public Guid Guid { get; set; }

public string FirstName { get; set; }
public string LastName { get; set; }

public DateTime Registration { get; set; }

public int SubdivId { get; set; }
public Subdiv Subdiv { get; set; }

and context with OnModelCreating method

modelBuilder.Entity<Realtor>(real => {
real.Property<Guid>(p => p.Guid)

real.Property<DateTime>(p => p.Registration)

real.HasOne(r => r.Subdiv)
.WithMany(s => s.Realtors)
.HasForeignKey(r => r.SubdivId);

I set default value for property Registration, but when I do an insert, I get Exception: cannot insert the value null into column Registration.

Answer Source

First of all, remove the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] for Restration. This could be the cause for your exception. If you don't want to make it nullable and want to set the value with your entity you could also:

public DateTime Restration { get; set; } = DateTime.Now;

Should work (I ain't got a VS 2015 here, so you have to test. Otherwise set the value for Restration in constructor.)

update: and remove at least this line

real.Property<DateTime>(p => p.Registration)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download