EF 配置多个数据库
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 配置多个数据库的更多相关文章
- EF 学习系列二 数据库表的创建和表关系配置(Fluent API、Data Annotations、约定)
上一篇写了<Entity Farmework领域建模方式 3种编程方式>,现在就Code First 继续学习 1.数据库表的创建 新建一个MVC的项目,在引用右击管理NuGet程序包,点 ...
- EF POWER TOOLS由数据库逆向CODE FIRST
EF POWER TOOLS由数据库逆向CODE FIRST 前言 利用db first的开发方式有很多可供选择的方案,一种可以用ado.net实体框架模型,由向导直接生成edmx,并生成数据库上下文 ...
- EF对于已有数据库的Code First支持
EF对于已有数据库的Code First支持 原文链接 本文将逐步介绍怎样用Code First的方式基于已有数据库进行开发.Code First支持你使用C#或者VB.Net定义类.并使用数据模型标 ...
- asp.net core 将配置文件配置迁移到数据库(一)
asp.net core 将配置文件配置迁移到数据库(一) Intro asp.net core 配置默认是项目根目录下的 appsettings.json 文件,还有环境变量以及 command l ...
- 6.翻译系列:EF 6 Code-First中数据库初始化策略(EF 6 Code-First系列)
原文链接:http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-firs ...
- 使用EF CodeFirst连接MySql数据库
如何使用EF CodeFirst连接MySql数据库? 我们这篇文章介绍怎么使用EF连接MySql 作者的环境 VS2017.Win10.MySql5.x 前言 一般在EF中,默认是使用SqlServ ...
- EF Code First更新数据库时报错:provider: SQL Network Interfaces, error: 26
在使用EF Code First更新数据库时报如下错误: 在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误.未找到或无法访问服务器.请验证实例名称是否正确并且 SQL Serv ...
- Entity Framework(五):使用配置伙伴创建数据库
在上一篇文章中讲了如何使用fluent API来创建数据表,不知道你有没有注意到一个问题.上面的OnModelCreating方法中,我们只配置了一个类Product,也许代码不是很多,但也不算很少, ...
- EF Code First Migrations数据库迁移
1.EF Code First创建数据库 新建控制台应用程序Portal,通过程序包管理器控制台添加EntityFramework. 在程序包管理器控制台中执行以下语句,安装EntityFramewo ...
随机推荐
- AtCoder Beginner Contest 075 D - Axis-Parallel Rectangle【暴力】
AtCoder Beginner Contest 075 D - Axis-Parallel Rectangle 我要崩溃,当时还以为是需要什么离散化的,原来是暴力,特么五层循环....我自己写怎么都 ...
- Codeforces 662D International Olympiad【贪心】
比赛的时候后缀长度在4位以内的时候分类讨论了一下,其实他们完全是一个套路的..并不需要讨论. 然后没有考虑前导0的情况,就wa了.. 题目链接: http://codeforces.com/probl ...
- Java练习 SDUT-1689_斐波那契?
斐波那契? Time Limit: 1000 ms Memory Limit: 32768 KiB Problem Description 给出一个数列的递推公式,希望你能计算出该数列的第N个数.递推 ...
- offsetheight 和clientheight、scrollheight、scrollTop区别
clientHeight:元素客户区的大小,指的是元素内容及其边框所占据的空间大小(经过实践取出来的大多是视口大小) scrollHeight: 滚动大小,指的是包含滚动内容的元素大小(元素内容的总高 ...
- python中'0b111'中的b 是什么意思
https://zhidao.baidu.com/question/987330764742072579.html binary,二进制的意思
- Springboot应用中@EntityScan和@EnableJpaRepositories的用法
在Springboot应用开发中使用JPA时,通常在主应用程序所在包或者其子包的某个位置定义我们的Entity和Repository,这样基于Springboot的自动配置,无需额外配置,我们定义的E ...
- Android教程-02 在程序中输出Log
视频教程,建议采用超清模式观看 在Android中一般都用Log输出日志,常见的有5个不同的级别 Log.v() Log.d() Log.i() Log.w() Log.e() 当然很多程序员还比较习 ...
- H3C 主机单播IP包发送
- URL的转义和解析
在开始python编程之前我们先来看看一个关与url的知识 在url中会有一些特殊字符,如果你写过cgi程序,并且提交一个表单去调用你的cgi,你会很清楚的 像?name=aiqier&age ...
- DOM事件和一些实用笔记
let el = document.body.querySelector("style[type='text/css'], style:not([type])");返回HTML文档 ...