1

I would like to manually insert id for all my entities. Is it possible to create some kind of convention or I have to set HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) (or add DatabaseGenerated attribute) for every entity ?

EDIT

There is a simpler way to do this then using accepted answer:

modelBuilder.Conventions.Remove<StoreGeneratedIdentityKeyConvention>();
Marka
  • 377
  • 1
  • 4
  • 17

1 Answers1

5

It's possible to create custom conventions in EntityFramework 6 as follows:

Create a convention class

public class ManualIdentityConvention : Convention
{
    public ManualIdentityConvention()
    {
        this.Properties<int>()
            .Where(p => p.Name.EndsWith("Id"))
            .Configure(p => p.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
    }
}

Add the convention to your DbContext

public class Context : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(new ManualIdentityConvention());
    }
}

EntityFramework 5

As for EntityFramework 5, I believe something similar can be achieved, but not via a convention class:

public class Context : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<int>()
            .Where(x => x.Name.EndsWith("Id"))
            .Configure(x => x.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
    }
}

In either case, neither approach is particularly surgical, but one could conceivably tighten up the convention by being more specific in one's where clause.

Does this help?

m.casey
  • 2,579
  • 17
  • 10