1.先创建两个DbContext

using System;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Reflection;
using Abp.EntityFramework; namespace TestProject.EntityFramework
{
public class TestProjectDbContext : AbpDbContext
{
//TODO: Define an IDbSet for each Entity... //Example:
//public virtual IDbSet<User> Users { get; set; } /* NOTE:
* Setting "Default" to base class helps us when working migration commands on Package Manager Console.
* But it may cause problems when working Migrate.exe of EF. If you will apply migrations on command line, do not
* pass connection string name to base classes. ABP works either way.
*/
public TestProjectDbContext()
: base("Default")
{ } /* NOTE:
* This constructor is used by ABP to pass connection string defined in TestProjectDataModule.PreInitialize.
* Notice that, actually you will not directly create an instance of TestProjectDbContext since ABP automatically handles it.
*/
public TestProjectDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{ } //This constructor is used in tests
public TestProjectDbContext(DbConnection existingConnection)
: base(existingConnection, false)
{ } public TestProjectDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{ } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var typesRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !(string.IsNullOrEmpty(type.Namespace))).Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
//删除级联
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
base.OnModelCreating(modelBuilder);
}
}
}

下面是新建的上下文,新建的DbContext不能含有DbContext(string nameOrConnectionString)构造函数,否则会被默认的连接名注入。

using Abp.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace TestProject.EntityFramework
{ public class TestSecondDbContext : AbpDbContext
{
//TODO: Define an IDbSet for each Entity...
public DbSet<AuditLog> AuditLog { get; set; }
//Example:
//public virtual IDbSet<User> Users { get; set; } /* NOTE:
* Setting "Default" to base class helps us when working migration commands on Package Manager Console.
* But it may cause problems when working Migrate.exe of EF. If you will apply migrations on command line, do not
* pass connection string name to base classes. ABP works either way.
*/
public TestSecondDbContext()
: base("Second")
{ } //This constructor is used in tests
public TestSecondDbContext(DbConnection existingConnection)
: base(existingConnection, false)
{ } public TestSecondDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{ } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var typesRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !(string.IsNullOrEmpty(type.Namespace))).Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
//删除级联
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
base.OnModelCreating(modelBuilder);
}
}
}

2.创建实体类并且配置映射

public class AuditLogMap : EntityTypeConfiguration<AuditLog>
{
public AuditLogMap()
{
ToTable("AuditLog");
HasKey(t => t.Id); Property(t => t.BrowserInfo).IsOptional().HasColumnType("varchar").HasMaxLength();
Property(t => t.ClientIpAddress).IsOptional().HasColumnType("nvarchar").HasMaxLength();
Property(t => t.ClientName).IsOptional().HasColumnType("varchar").HasMaxLength();
Property(t => t.CustomData).IsOptional().HasColumnType("varchar").HasMaxLength();
Property(t => t.Exception).IsOptional().HasColumnType("varchar").HasMaxLength();
Property(t => t.ExecutionDuration).IsOptional();
Property(t => t.ExecutionTime).IsOptional();
Property(t => t.MethodName).IsOptional().HasColumnType("varchar").HasMaxLength();
Property(t => t.Parameters).IsOptional().HasColumnType("nvarchar").HasMaxLength();
Property(t => t.ServiceName).IsOptional().HasColumnType("varchar").HasMaxLength();
}
}
public abstract class TestProjectRepositoryBase<TEntity, TPrimaryKey> : EfRepositoryBase<TestProjectDbContext, TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
protected TestProjectRepositoryBase(IDbContextProvider<TestProjectDbContext> dbContextProvider)
: base(dbContextProvider)
{ } //add common methods for all repositories
} public abstract class TestProjectRepositoryBase<TEntity> : TestProjectRepositoryBase<TEntity, int>
where TEntity : class, IEntity<int>
{
protected TestProjectRepositoryBase(IDbContextProvider<TestProjectDbContext> dbContextProvider)
: base(dbContextProvider)
{ } //do not add any method here, add to the class above (since this inherits it)
}
 public abstract class TestSecondRepositoryBase<TEntity, TPrimaryKey> : EfRepositoryBase<TestSecondDbContext, TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
protected TestSecondRepositoryBase(IDbContextProvider<TestSecondDbContext> dbContextProvider)
: base(dbContextProvider)
{ } //add common methods for all repositories
} public abstract class TestSecondRepositoryBase<TEntity> : TestSecondRepositoryBase<TEntity, int>
where TEntity : class, IEntity<int>
{
protected TestSecondRepositoryBase(IDbContextProvider<TestSecondDbContext> dbContextProvider)
: base(dbContextProvider)
{ } //do not add any method here, add to the class above (since this inherits it)
}

3.执行命令

First step
========== enable-migrations -ContextTypeName TestProjectDbContext -MigrationsDirectory Migrations enable-migrations -ContextTypeName TestSecondDbContext -MigrationsDirectory MigrationsSecond Second Step
=========== add-migration -ConfigurationTypeName TestProject.Migrations.Configuration "InitialCreate" "InitialCreate" add-migration -ConfigurationTypeName TestProject.MigrationsSecond.Configuration "InitialCreate" Third Step
========== update-database -ConfigurationTypeName TestProject.Migrations.Configuration -verbose update-database -ConfigurationTypeName TestProject.MigrationsSecond.Configuration -verbose

4 开启MSDTC

MSDTC(分布式交易协调器),协调跨多个数据库、消息队列、文件系统等资源管理器的事务。该服务的进程名为Msdtc.exe,该进程调用系统Microsoft Personal Web Server和Microsoft SQL Server。该服务用于管理多个服务器 .
位置:控制面板--管理工具--服务--Distributed Transaction Coordinator
依存关系:Remote Procedure Call(RPC)和Security Accounts Manager
建议:一般家用计算机涉及不到,除非你启用Message Queuing服务,可以停止。
解决办法: . 在windows控制面版-->管理工具-->服务-->Distributed Transaction Coordinator-->属性-->启动
.在CMD下运行"net start msdtc"开启服务后正常。 注:如果在第1步Distributed Transaction Coordinator 无法启动,则是因为丢失了日志文件,重新创建日志文件,再启动就行了。重新创建 MSDTC 日志,并重新启动服务的步骤如下:
() 单击"开始",单击"运行",输入 cmd 后按"确定"。
() 输入:msdtc -resetlog (注意运行此命令时,不要执行挂起的事务)
() 最后输入:net start msdtc 回车,搞定!

EF 配置多个数据库的更多相关文章

  1. EF 学习系列二 数据库表的创建和表关系配置(Fluent API、Data Annotations、约定)

    上一篇写了<Entity Farmework领域建模方式 3种编程方式>,现在就Code First 继续学习 1.数据库表的创建 新建一个MVC的项目,在引用右击管理NuGet程序包,点 ...

  2. EF POWER TOOLS由数据库逆向CODE FIRST

    EF POWER TOOLS由数据库逆向CODE FIRST 前言 利用db first的开发方式有很多可供选择的方案,一种可以用ado.net实体框架模型,由向导直接生成edmx,并生成数据库上下文 ...

  3. EF对于已有数据库的Code First支持

    EF对于已有数据库的Code First支持 原文链接 本文将逐步介绍怎样用Code First的方式基于已有数据库进行开发.Code First支持你使用C#或者VB.Net定义类.并使用数据模型标 ...

  4. asp.net core 将配置文件配置迁移到数据库(一)

    asp.net core 将配置文件配置迁移到数据库(一) Intro asp.net core 配置默认是项目根目录下的 appsettings.json 文件,还有环境变量以及 command l ...

  5. 6.翻译系列:EF 6 Code-First中数据库初始化策略(EF 6 Code-First系列)

    原文链接:http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-firs ...

  6. 使用EF CodeFirst连接MySql数据库

    如何使用EF CodeFirst连接MySql数据库? 我们这篇文章介绍怎么使用EF连接MySql 作者的环境 VS2017.Win10.MySql5.x 前言 一般在EF中,默认是使用SqlServ ...

  7. EF Code First更新数据库时报错:provider: SQL Network Interfaces, error: 26

    在使用EF Code First更新数据库时报如下错误: 在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误.未找到或无法访问服务器.请验证实例名称是否正确并且 SQL Serv ...

  8. Entity Framework(五):使用配置伙伴创建数据库

    在上一篇文章中讲了如何使用fluent API来创建数据表,不知道你有没有注意到一个问题.上面的OnModelCreating方法中,我们只配置了一个类Product,也许代码不是很多,但也不算很少, ...

  9. EF Code First Migrations数据库迁移

    1.EF Code First创建数据库 新建控制台应用程序Portal,通过程序包管理器控制台添加EntityFramework. 在程序包管理器控制台中执行以下语句,安装EntityFramewo ...

随机推荐

  1. docker images列出镜像

    命令:docker images Usage: docker images [OPTIONS] [REPOSITORY[:TAG]] List images Options: -a, --all Sh ...

  2. 浅析调用android的content provider(一)

            在Android下,查询联系人.通话记录等,需要用到content provider.但是,调用content provider时,Android框架内部是如何做的呢?这一系列文章就是 ...

  3. linux下修改gcc编译器版本

    可以使用如下命令行来让 gcc 选择不同的 C++ 版本: g++ -std=c++11 main.cpp 在你的系统中,由于编译器或是编译器设定上的差别,操作也许有所不同.    

  4. Istio on ACK集成生态(1): 集成TSDB助力可观测性存储

    阿里云容器服务Kubernetes(简称ACK)支持一键部署Istio,可以参考文档在ACK上部署使用Isito.Istio on ACK提供了丰富的监控能力,为网格中的服务收集遥测数据,其中Mixe ...

  5. 阿里云应用实时监控 ARMS 再升级,支持 Prometheus 开源生态

    摘要: 应用实时监控服务 (ARMS) 是一款APM类的监控产品. 用户可基于 ARMS 的前端.应用.自定义监控,快速构建实时的应用性能和业务监控能力.ARMS 让所有性能问题“一屏了然”,不遗余力 ...

  6. url地址栏参数<==>对象(将对象转换成地址栏的参数以及将地址栏的参数转换为对象)的实用函数

    /** * @author web得胜 * @param {Object} obj 需要拼接的参数对象 * @return {String} * */ function obj2qs(obj) { i ...

  7. Getting started with the basics of programming exercises_2

    1.编写简单power函数 #include<stdio.h> int power(int m, int n); // test power function int main(void) ...

  8. H3C CSMA/CD冲突检测和退避

  9. Lifecycle mapping "org.eclipse.m2e.jdt.JarLifecycleMapping" Eclipse Maven报错

    eclipse 项目中报错Lifecycle mapping "org.eclipse.m2e.jdt.JarLifecycleMapping" is not available, ...

  10. Bi-LSTM-CRF for Sequence Labeling

    做了一段时间的Sequence Labeling的工作,发现在NER任务上面,很多论文都采用LSTM-CRFs的结构.CRF在最后一层应用进来可以考虑到概率最大的最优label路径,可以提高指标. 一 ...