1

In my application (database-first) the primary keys are always created by client, not by the underlying database.

In Entity Framework v4 each Entity had it's EntityKey property that could be set manually.

However, I can't find it anymore in EF6?

Is there any specific reason why?

I don't want to call ctx.SaveChanges() only to have an Entity's key set as this means a call to the database.

I'm also wondering why ObjectContext.CreateEntityKey is gone?!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
KingKerosin
  • 3,639
  • 4
  • 38
  • 77

1 Answers1

0

If You're using POCO's - here's a sample how it could be done

public class ChronosItem 
{
    [Column, Key, Required, MaxLength(26), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Id { get;  set; }
    ....

In case You cant adjust Your entities

override the "OnModelCreating" method on Your context.. like so..

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ChronosItem >()
                .HasKey(p => p.Id)
                .Property(p => p.Id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Marty
  • 3,485
  • 8
  • 38
  • 69
  • I'm using `database-first` approach. So, the `entities` are generated and I can't update each of them each time I update the database. – KingKerosin Jan 20 '16 at 19:54
  • That's why Your EntitiesContext class is generated as 'Partial'. So there would be a place to put Your customisations that would not get overWriten when You update the model from DB. Another thing - if EF thinks that the ID is autogenerated - Identity specification in SQL must be set to true (take a look at column properties in SQL) – Marty Jan 20 '16 at 19:59
  • In my case - if I generate the model from DB, the prop ID (for ChronosItem) has StoreGeneratedPattern = None – Marty Jan 20 '16 at 19:59