Entity Framework Core Auto Generated guid

asp.net-core-2.1 c# entity-framework-core

Question

Can some One guide me I want primeryKey of a table as guid having db generated value on insert.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

but it's giving error

The seed entity for entity type 'User' cannot be added because there was no value provided for the required property 'Id'.

Here is my actual model classes and DbContxt class:

public class BaseModel
{
     [Key]
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public Guid Id { get; set; }

     [Required]
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     public DateTime CreatedOn { get; set; } = DateTime.UtcNow;


     [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
     public DateTime? UpdatedOn { get; set; }

     [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
     public DateTime LastAccessed { get; set; }
 }

 public class User : BaseModel
 {
        [Required]
        [MinLength(3)]
        public string Name { get; set; }

        [Required]
        [MinLength(3)]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [MinLength(6)]
        public string Password { get; set; }
  }

Then in the DbContxt:

public class DBContaxt : DbContext
    {
        public DBContaxt(DbContextOptions<DBContaxt> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder mb)
        {
            base.OnModelCreating(mb);

            mb.Entity<User>().HasData(
                new User() { Email = "Mubeen@gmail.com", Name = "Mubeen", Password = "123123" },
                new User() { Email = "Tahir@gmail.com", Name = "Tahir", Password = "321321" },
                new User() { Email = "Cheema@gmail.com", Name = "Cheema", Password = "123321" }
                );
        }

        public DbSet<User> User { get; set; }
    }

Any help please!

1
9
11/27/2018 7:09:32 AM

Accepted Answer

The problem you are experiencing is not specific for autogenerated Guids. The same happens for any autogenerated key values, including the commonly used auto increment (identity) columns.

It's caused by a specific Data Seeding (HasData) requirement:

This type of seed data is managed by migrations and the script to update the data that's already in the database needs to be generated without connecting to the database. This imposes some restrictions:

  • The primary key value needs to be specified even if it's usually generated by the database. It will be used to detect data changes between migrations.
  • Previously seeded data will be removed if the primary key is changed in any way.

Note the first bullet. So while for normal CRUD your PK will be auto generated, you are required to specify it when using HasData fluent API, and the value must be constant (not changing), so you can't use Guid.NewGuid(). So you need to generate several Guids, take their string representation and use something like this:

mb.Entity<User>().HasData(
    new User() { Id = new Guid("pre generated value 1"), ... },
    new User() { Id = new Guid("pre generated value 2"), ... },
    new User() { Id = new Guid("pre generated value 3"), ... }
    );
9
11/27/2018 8:02:18 AM

Popular Answer

[DatabaseGenerated(DatabaseGeneratedOption.Identity)] on GUID field works on Entity Framework 6.x, may be not in EF Core yet!

So the solution is:

1) First write your BaseModel class as follows:

public class BaseModel
{
    [Key]
    public Guid Id { get; set; }

    public DateTime CreatedOn { get; set; } = DateTime.UtcNow;

    public DateTime? UpdatedOn { get; set; }

    public DateTime LastAccessed { get; set; }
}

2) Then OnModelCreating() method in your DbContext should be as follows:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
      base.OnModelCreating(modelBuilder);

      modelBuilder.Entity<YourEntity>().Property(x => x.Id).HasDefaultValueSql("NEWID()");

      modelBuilder.Entity<User>().HasData(
            new User() { Id  = Guid.NewGuid(), Email = "Mubeen@gmail.com", Name = "Mubeen", Password = "123123" },
            new User() { Id = Guid.NewGuid(), Email = "Tahir@gmail.com", Name = "Tahir", Password = "321321" },
            new User() { Id = Guid.NewGuid(),  Email = "Cheema@gmail.com", Name = "Cheema", Password = "123321" }
            );
 }

Now create a brand new migration and update the database accordingly. Hope your problem will be solved!



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow