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 ...
随机推荐
- 看看国外的JavaScript题目
---恢复内容开始--- 题目一 (function(){ return typeof arguments;})(); 答案:“object” arguments是对象,伪数组有两件事要注意这里 ...
- 云上快速搭建Serverless AI实验室
Serverless Kubernetes和ACK虚拟节点都已基于ECI提供GPU容器实例功能,让用户在云上低成本快速搭建serverless AI实验室,用户无需维护服务器和GPU基础运行环境,极大 ...
- Laravel的请求声明周期
声明周期概述# 开始# public/index.php 文件是所有对Laravel应用程序的请求的入口点.而所有的请求都是经由你的Web服务器(Apache/Nginx) 通过配置引导到这个文件.i ...
- web移动开发小贴士
1.判断手机类型 var u = navigator.userAgent; || u.indexOf(; //android var isiOS = !!u.match(/\(i[^;]+;( U;) ...
- Pytorch的默认初始化分布 nn.Embedding.weight初始化分布
一.nn.Embedding.weight初始化分布 nn.Embedding.weight随机初始化方式是标准正态分布 ,即均值$\mu=0$,方差$\sigma=1$的正态分布. 论据1——查看 ...
- laravel 增加不存在数据库的字段
有时候您可能想要增加不存在数据库字段的属性数据.这时候只要定义一个获取器即可: public function getIsAdminAttribute() { return $this->att ...
- 十分钟学会 Fiddler
一.Fiddler介绍 Fiddler是一个http抓包改包工具,fiddle英文中有"欺骗.伪造"之意,与wireshark相比它更轻量级,上手简单,因为只能抓http和http ...
- 使用php函数ini_set()重新设置某个配置的设置值
使用PHP的ini_set()函数 ini_set (PHP 4, PHP 5, PHP 7) ini_set — 为一个配置选项设置值 说明 string ini_set ( string $var ...
- HTTP协议详解以及URL具体访问过程(转载)
https://blog.csdn.net/f45056231p/article/details/82533490
- springboot2.04与activiti 6.0集成
本文就不对activiti做解释,下面直接看项目集成 以下顺序方面根据我的理解来,可以先从第二章看,再看第一张与第三章 增加activiti表的API,备注用. 目录 一.springboot2.X集 ...