1

I'm using EntityFramework Code-First with a context that has a model like:

public class Person {
  public int ID {get;set;}
  public string Name {get;set;}
}

with a context like

public class DataContext: DbContext {
   public DbSet<Person> People {get;set;}
}

And this gets saved into DatabaseA. When I insert a new person, it auto-generates an ID for that person. I need to have a DatabaseB that has the exact same structure, but without the ID auto-generation. I want to transfer some records from DatabaseA to DatabaseB but without DatabaseB generating new IDs. I know that I can wrap

[DatabaseGenerated(DatabaseGeneratedOption.None)]

around the ID property, but I only want it to apply to DatabaseB without affecting DatabaseA.

So the only solution I've come up with so far is to have a new model

public class PersonB : Person {
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public new int ID { get; set; }
}

and a new context

public class DataContextB : DbContext { 
     public DbSet<PersonB> People {get;set;}
}

But this is a bit of a nuisance, as I'd have to maintain two sets of fairly identical models. Ideally, I'd like to be able to do something in using(var db = new DataContextB) { db. }

RamblerToning
  • 926
  • 2
  • 13
  • 28
  • 2
    make two context subclasses, one of which configures all keys as `DatabaseGeneratedOption.None` by *fluent mapping*, not data annotations. A bit like [this](https://stackoverflow.com/a/47231878/861716). – Gert Arnold Nov 16 '17 at 13:06
  • At most you would need a new Context, not a complete Model. You can specify the Identity stuff in `override OnModelCreating()` – H H Nov 16 '17 at 13:06
  • You can use fluent api to make your ID not identical. – Saadi Nov 16 '17 at 13:07
  • we use the two lines var option = Writeversion ? DatabaseGeneratedOption.None : DatabaseGeneratedOption.Identity; modelBuilder.Types().Configure(x => x.Property(y => y.Id).HasDatabaseGeneratedOption(option));, where WriteVersion is a flag set in the constructor of the context. this allows the same context to have differing models. – DevilSuichiro Nov 16 '17 at 14:01

1 Answers1

3

You can override OnModelCreating function of DbContext and write some fluent api code.

Please have a look on this approach

public class DataContextB : DbContext
{
    public DbSet<Person> People {get;set;}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().Property(t => t.ID)
                    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        base.OnModelCreating(modelBuilder);
    }
}
Saadi
  • 2,211
  • 4
  • 21
  • 50