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. Android学习:导入工程时报错The import android cannot be resolved

    今天在导入别人的工程时,出现了一个这个问题The import android cannot be resolved 就是找不到import android.support.v7.app.Action ...

  2. CENTOS7安装R语言环境

    CENTOS7安装R语言环境 yum install texinfo.x86_64 yum install texlive.x86_64 cd /opt wget https://mirrors.tu ...

  3. call和apply用途与使用方法

    当你看代码时,经常会看到以下情形:(在这个博客里面,参数context是执行上下文的意思,params是参数的意思) Object.prototype.toString.call(context, p ...

  4. React Native声明属性和属性确认

    属性声明 因为用React Native创建的自定义组件可以复用, 我们开发过程中可能一个项目组有多个人同时开发,其他同事可能会用到我们自定义的组件, 但是他们使用的时候很容易忘记使用某些属性,这时候 ...

  5. Oracle基础学习4--Oracle权限传递

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/wang379275614/article/details/32215325 以下将用一个实例来解说: ...

  6. iptables 伪装(Masquerading)

    「偽装」是一种特殊的SNAT操作:将来自其它电脑的包的来源位址改成自己的位址:请注意,由於入替的来源位址是自动決定的(执行SNAT的主机的IP位址).所以,如果它改变了,仍在持续中的旧连線将会失效.「 ...

  7. 微信授权登录-微信公众号和PC端网站

    https://blog.csdn.net/qq_34664239/article/details/79107529 一.微信公众号授权登录——微信公众平台 微信授权登录,并调用后台接口,获取用户信息 ...

  8. [kuangbin带你飞]专题九 连通图E POJ 3177 Redundant Paths

    这个题最开始我想的是,直接缩点求双连通分量,连接这些双联通分量不就行了吗? 但是其实是不对的,双连通内部双联通,我们如果任意的连接一条边在这些双联通分量之间,他们之间有没有桥其实并不知道. 我应该是求 ...

  9. Timer更新UI的合理办法

    using System; using System.Windows; using System.Timers; using System.Windows.Threading; namespace T ...

  10. supersockets命令过滤器

    关键字: 命令过滤器, 命令, 过滤器, OnCommandExecuting, OnCommandExecuted SuperSocket 中的命令过滤器看起来有些像 ASP.NET MVC 中的 ...