Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Entity Framework 4 Code First have support for identity generators like NHibernate?

This question, asked a year ago, is similar: Does the Entity Framework 4 support generators for id values like NHibernate?

But what I'd like to know is if the code first CTP adds support for identity generation strategies. If not, does anyone know a good extension point in EF to implement something similar?

I'm currently working with model classes which use GUID as the identifier. When inserting using EF they retain their Guid.Empty initial values. I know that you can set a default value for the column in the DB to newid() but that defeats the purpose of client-side identity generation.

Is Entity Framework just not mature enough to be used in a distributed, disconnected system?

like image 818
joshperry Avatar asked Mar 11 '11 16:03

joshperry


1 Answers

No, Entity framework code-first is still just nice wrapper around EFv4. There are no NHibernate like generators. If you want client side Id generator you will have to override SaveChanges in derived DbContext and implement your own logic of assigning Ids to new entities.

Edit:

Some high level example:

public class Context : DbContext
{
    // Helper for example
    // DO NOT USE IN REAL SCENARIOS!!!
    private static int i = 0; 

    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.Id);
        // Turn off autogeneration in database
        modelBuilder.Entity<MyEntity>()
                    .Property(e => e.Id)
                    .HasDatabaseGeneratedOption(HasDatabaseGeneratedOption.None);

        // Other mapping
    }

    public override int SaveChanges()
    {
        foreach (var entry in ChangeTracker.Entries<MyEntity>()
            .Where(e => e.State == EntityState.Added))
        {
            // Here you have to add some logic to generate Id
            // I'm using just static field
            entry.Entity.Id = ++i;  
        }

        return base.SaveChanges();
    }
}

public class MyEntity
{
    public int Id { get; set; }
    // Other properties
}
like image 148
Ladislav Mrnka Avatar answered Nov 06 '22 05:11

Ladislav Mrnka