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?
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
}
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