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
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
}
No.
Mine Entity Framework 4.1.10715 installed by NuGet. maybe you could use attribute
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id {get;set;}
please see (The full list of annotations supported in EF 4.1 : CTRL+F in page) here.
[Key]
public string Id { get; set; }
and then use new GUID ToString
Units.Add( new Unit(){Id=Guid.NewGuid().ToString(), Name="123"});