【问题标题】:Synchronize data of two dbcontexts (Different providers)同步两个 dbcontexts 的数据(不同的提供者)
【发布时间】:2014-02-07 21:34:48
【问题描述】:

我正在使用代码优先和 ef 6 创建一个小项目,但现在我遇到了一个问题:

客户想要一个MySql数据库(我们称之为OnlineDbContext)和一个SqlServerCe4.0 with(我们称之为OfflineCotext),并希望将离线与在线(方向,在线 -> 离线)。

到目前为止,我创建了一个 BaseContext,以及另外两个上下文(OfflineContextOnlineContext 继承自 BaseContext) .

他们工作得很好。我还创建了一个算法,它从 OnlineContext 复制所有实体(和关系),并使用单个 SaveChanges() 保存在 OfflineContext 中。

这可行,但有一个问题:

如果一个实体有一个 AutoID PK,例如 3 个实体(Id:1、Id:2、Id:4 - Id3 已删除), 克隆上下文将包含具有 (Id:1, Id:2, Id:3) 的实体。

我的问题:有没有办法强制 AI PK 的值,或者至少强制跳过 ID?或者,是否有通过 DbContexts 将数据库复制到另一个数据库的最佳方法?

我在这里找到了一个有趣的post,关于以编程方式生成 ID,但它是使用 Java 和 Hibernate。如果我能用 ef 做这样的事情,我想我可以解决这个问题。

编辑:

我尝试使用Gert Sugestion,但是有一个问题:

如果我把这段代码放在 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));
        }

它确实有效,但这会导致我的 OnlineContext 没有 AutoIds,这不是目标,所以我只将这段代码放在我的 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));
        }

现在可以了,谢谢

【问题讨论】:

  • 我认为如果离线数据库没有生成的Ids会更容易。
  • @GertArnold 我尝试了您的建议,请参阅编辑

标签: c# entity-framework ef-code-first code-first dbcontext


【解决方案1】:

使用 Gert Arnold 的建议,我在 OfflineContext 上使用 Fluent API 进行了一些更改,以不使用 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));
        }

现在它们完全同步了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多