实体框架故意禁用自动增量 [英] Entityframework disable autoincrement on purpose

查看:72
本文介绍了实体框架故意禁用自动增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写将替换旧应用程序的应用程序,因此在第一步中很不幸,我必须同步数据

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

我的班级看起来像这样

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

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

我正在为此项目使用sqlite,它允许指定ProgramIndex,否则它将为我产生。

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

但是,如果我尝试使用entityframework插入并指定索引,它将失败。
我可以通过在索引属性中添加属性来解决该问题

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.

所以我的问题是有什么办法可以动态设置DatabaseGeneratedOption.None吗?

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

推荐答案

对我来说,最简单的方法是从数据库上下文扩展

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);
        }
    }

下面是想法,为了同步,我使用了不同的方法上下文,以加快速度,实际上,在这里覆盖模型创建是我所能做的最好的事情,因此,我使用NoTrackingFlymarkOfflineContext负责索引和EntityState

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

这篇关于实体框架故意禁用自动增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆