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!
[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:2) Then
OnModelCreating()
method in yourDbContext
should be as follows:Now create a brand new migration and update the database accordingly. Hope your problem will be solved!
Rather than manually updating the migration, you could also implement an update in the OnModelCreating that adds it into the migration for you, e.g.
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: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 useGuid.NewGuid()
. So you need to generate several Guids, take their string representation and use something like this:You can use
defaultValueSql: "newid()"
in your Code First Migration file.For Example;
GUID
is handled byIdentity framework
and not by EF, so to use GUID you need to do as the followingand then prepare the model before insert into table