I want to use EF4 to map entity to a table that has sequential guid as a PK. According to this post http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/ EF4 supports this but with edmx mapping. Is there a way to use the server generated Guids when using EF4 Code First and if yes how?
The other items are covered by my approach, a sequential guid can be generated from code without need for DB access (also if only for Windows) and it's unique in time and space.
GUIDs can be considered as global primary keys. Local primary keys are used to uniquely identify records within a table. On the other hand, GUIDs can be used to uniquely identify records across tables, databases, and servers.
The Entity Framework Core Fluent API HasComputedColumnSql method is used to specify that the property should map to a computed column. The method takes a string indicating the expression used to generate the default value for a database column.
Yes, you must map your Key property. Let's assume you have an entity like:
public class MyEntity
{
public virtual Guid Key { get; set; }
...
}
Then you can define DbContext
derived class like:
public class Context : DbContext
{
public DbSet<MyEntity> MyEntities { get; private set; }
public Context()
: base("connection")
{
MyEntities = Set<MyEntity>();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyEntity>().HasKey(e => e.Key);
modelBuilder.Entity<MyEntity>()
.Property(e => e.Key)
.HasDatabaseGeneratedOption(DatabaseGenerationOption.Identity);
// Other mapping
}
}
Or you can simply define your entity with Data Annotations:
public class MyEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual Guid Key { get; set; }
...
}
Edit:
This works if the mapping is used with existing database but if you want EF code-first to create database for you it will use normal (not sequential) guids! Check this question for possible solutions in case of database generation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With