Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Sequential Guid as a key when using Entity Framework Code First

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?

like image 862
Stilgar Avatar asked Mar 17 '11 12:03

Stilgar


People also ask

Can the GUID be sequential?

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.

Can we use GUID as primary key in a table?

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.

How can we specify computed generated column in Entity Framework?

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.


1 Answers

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.

like image 140
Ladislav Mrnka Avatar answered Nov 09 '22 00:11

Ladislav Mrnka