Vova Bilyachat
Vova Bilyachat

Reputation: 19494

Entityframework disable autoincrement on purpose

I am writing application which will replace old app so on first steps, unfortunately, i must synchronize data

My class look like that

  public class Program
    {
        [Key]
        public int ProgramIndex { get; set; }

        public string ProgramName { get; set; }
        public string EnglishName { get; set; }
        public string ExtraData { get; set; }
    }

I am using sqlite for this project which allow to specify ProgramIndex or it will generate for me.

But if i try to insert with entityframework and specifying index it will fail. I can fix that using by adding attribute to index properties

[DatabaseGenerated(DatabaseGeneratedOption.None)]

But the problem is that i need to disable autoincrement only when i am synchronizing data.

So my question is is this there any way to set DatabaseGeneratedOption.None on fly?

Upvotes: 4

Views: 6358

Answers (1)

Vova Bilyachat
Vova Bilyachat

Reputation: 19494

The easiest way for me to do is to extend from my db context

 public class NoTrackingFlymarkOfflineContext : FlymarkOfflineContext
    {
        public NoTrackingFlymarkOfflineContext() : base("FlymarkOfflineContext")
        {
            Configuration.AutoDetectChangesEnabled = false;
            Configuration.ValidateOnSaveEnabled = false;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Viddil>()
                .Property(p => p.ViddilIndex)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }
    }

Idea is following, that for synchronization i am using different context, to speed up, and actually here overriding modelcreation is the best what i can do, so as sinse i am using NoTrackingFlymarkOfflineContext i am responsible for indexes and EntityState

Upvotes: 6

Related Questions