Stilgar
Stilgar

Reputation: 23611

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?

Upvotes: 6

Views: 7847

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

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.

Upvotes: 12

Related Questions