Question

I'm creating a small project using code first and ef 6, but now i'm facing a problem:

The client want a MySql database (let's call it OnlineDbContext) and a SqlServerCe4.0 with (let's call it OfflineCotext), and want to syncronize the offline with the online (Direction, Online -> Offline).

So far i created a BaseContext, and two more contexts (OfflineContext and OnlineContext inheriting from BaseContext).

They work fine. Also i created a algorithm that copy all the entities (and relationships) from a OnlineContext and saves in a OfflineContext with a single SaveChanges().

This works, but there is one problem:

If a entity has a AutoID PK, and for example 3 entites (Id:1, Id:2, Id:4 - Id3 deleted), the clone context will have entities with (Id:1, Id:2, Id:3).

My question: is there a way to force the value of a AI PK, or at least, force a skip of a ID? or yet, is there a best way to copy a database to another database through DbContexts?

I found here a interesting post about programatically generate IDs, but it's with Java and Hibernate. If i could do something like this with ef, i think i may solve the problem.

EDIT:

I tried to use the Gert Sugestion, but there is a problem:

if i put this piece of code in the BaseContext:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

            modelBuilder.Properties().Where(p => p.Name.ToLower().Contains("id"))
                    .Configure(p => p.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
        }

It really works, but this cause my OnlineContext to not have AutoIds and thats isn't the objective, so i put this piece of code only inside my OfflineContext:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Properties().Where(p => p.Name.ToLower().Contains("id"))
                    .Configure(p => p.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
        }

Now its works, thanks

Était-ce utile?

La solution

Using Gert Arnold suggestion, I made some changes using Fluent API on my OfflineContext to not use AutoID:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Properties().Where(p => p.Name.ToLower().Contains("id"))
                    .Configure(p => p.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
        }

Now they are perfectly synchronized.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top