EntityFramework Core 怎么mycat实现读写分离离

温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
.net 与商业观察者
.net架构QQ群:
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
阅读(429)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
loftPermalink:'',
id:'fks_',
blogTitle:'NOP中EF读写分离设计',
blogAbstract:'\r\n一、增加IReadDbContext 接口\r\nusing System.Collections.Gusing System.Data.Eusing Nop.C\r\nnamespace Nop.Data{&&& public interface IReadDbContext&&& {&&&&&&& /// &summary&&&&&&&& /// Get DbSet&&&&&&& /// &/summary&&&&&&&& /// &typeparam name=\"TEntity\"&Entity type&/typeparam&&&&&&&& /// &returns&DbSet&/returns&',
blogTag:'nop中ef读写分离设计',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:8,
publishTime:3,
permalink:'blog/static/',
commentCount:2,
mainCommentCount:2,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'.net 与商业观察者\r\n.net架构QQ群:',
hmcon:'0',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}12:18 提问
.net Core EF 如何生成数据库视图模型
我在EF的项目中使用了这条命令
Scaffold-DbContext
"Data Source=.;Initial Catalog=EFCore_User ID=Password=sa.123" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
但是只能生成数据库表的模型,请问需要加什么参数,或者使用什么命令才能生成出数据库视图的模型
按赞数排序
按照这个帖子的回答,ef codefirst不能生成视图,但是可以嵌入sql语句,让它创建view
其他相似问题学习EntityFrameworkCore 1.0 笔记 (1) 构建应用程序 - 简书
学习EntityFrameworkCore 1.0 笔记 (1) 构建应用程序
EntityFramework Core 1.0 即原来的EF7.0更名,从.Net Framework平台向.Net Core平台的更新.吐槽一下,既然.Net Framework更名为.Net Core的话,EntityFramework为啥不更名为EntityCore,弄得名字越来越长,多打9个字母也累啊.
项目地址:官方文档:
关于本笔记
本笔记会以Ubuntu平台开发,数据库采用多种数据库(包括Sqlite,SQL Server和Npgsql),并在.为了纯粹学习EntityFramework Core(以下简称EFCore),代码将以Console形式开发,剥离掉ASP.NET等部分.开始之前,先下载所需要的包
.Net Core安装参考:
Sqlite的Ubuntu驱动:
$ sudo apt-get install libsqlite3-dev
本篇将简单构建一个EFCore应用程序,并插入一条数据。
创建EFCore Console项目
$ dotnet new
Created new C# project in /home/yotsuki/code/EFCoreLearn/learn01.
修改配置文件
在project.json的dependencies节点中加入引用,
"Microsoft.EntityFrameworkCore": "1.0.0-rc2-final",
"Microsoft.EntityFrameworkCore.Sqlite": "1.0.0-rc2-final",
"Microsoft.EntityFrameworkCore.Tools": {
"type":"build",
"version": "1.0.0-preview1-final"
并在framework中加入"portable-net452+win81"
"frameworks": {
"netcoreapp1.0": {
"imports": ["dnxcore50","portable-net452+win81"]
这里我们先用Sqlite为例子,修改完成后,输入命令
$ dotnet restore
将自动下载所需要的包,如果是第一次下载,会比较慢,请耐心等待
添加一个DbContext
新建一个文件SqliteContext.cs
using Microsoft.EntityFrameworkC
public class SqliteContext:DbContext
public SqliteContext():base(){}
public SqliteContext(DbContextOptions&SqliteContext& options) : base(options) { }
我们在使用EF6.x的时候,DbContext默认会读取App.config/Web.config中配置的同名连接字符串。但在EFCore中并不如此。由于.NET Core是一个真正模块化的平台,读取配置文件也需要自己去引用包。这里我先按照官方文档中提供的方法写入连接字符串
调用前传入
var builder = new DbContextOptionsBuilder&SqliteContext&();
builder.UseSqlite("Filename=./learn01.db");
using (var context = new SqliteContext(builder.Options)) {
重写DbContext的OnConfiguring方法
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseSqlite("Filename=./learn01.db");
添加一个实体
新建一个实体类User.cs
public class User
public Guid ID { }
public string Name { }
public string Password { }
并将实体加入SqliteContext中
public DbSet&User& Users { }
迁移功能(Migration)在EF6.x已经有了,CodeFirst开发中迁移功能可以方便的进行数据库模型的变更。在EF6.x中,Sqlite的驱动并不支持迁移,通常我们需要自己去写一个迁移功能。但这次EFCore提供的Sqlite驱动已经能够进行迁移了。要使用迁移功能需要先在project.json中添加工具支持
"tools": {
"Microsoft.EntityFrameworkCore.Tools": {
"imports": [ "portable-net451+win8" ],
"version": "1.0.0-preview1-final"
再restore后就可以使用命令了
$ dotnet restore
$ dotnet ef -h
Paste_Image.png
使用migrations add命令来添加迁移
$ dotnet ef migrations add Init
Project learn01 (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
Done. To undo this action, use 'ef migrations remove'
此命令对应EF6.x的Add-Migration命令添加迁移完成后,会在项目目录中新建一个Migrations目录和相应的迁移类和EF6.X一样,AddMigration之后需要update才会体现到数据库中
$ dotnet ef database update
Project learn01 (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
Applying migration '26_Init'.
完成迁移,我们来看下数据库
Paste_Image.png
数据库生成在bin/Debug/netcoreapp1.0/ 目录下其中包含两个表,“Users”和"__EFMigrationsHistory"表。“Users”不用多说,就是我们添加的实体表。"__EFMigrationsHistory"是迁移记录表,查询一下可以看到,其中已经有了一条数据,对应着我们本次的迁移。EFCore的迁移记录相对与EF6.x简单了一些,这里我推断EFCore并没有根据Model改变的一些操作。下图是EF6.1.2的迁移记录表,对比一下就发现目前EFCore的设计更加纯粹
Paste_Image.png
简单的添加一条记录
接下来,我们要为数据库添加第一条记录我们修改Program.cs
public static void Main(string[] args)
using (var context = new SqliteContext()) {
context.Users.Add(new User(){ Name="yotsuki",Password="123456"});
var result = context.SaveChanges();
if (result & 0) {
Console.WriteLine("1 row installed.");
Console.WriteLine("install failed.");
然后运行命令
$ dotnet build
$ dotnet run
Project learn01 (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
1 row installed.
我们再看下数据库
Paste_Image.png
一条数据已插入(Guid因为是二进制存储,显示有一些问题)
其他数据库
Sql Server
在project.json添加引用
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
在OnConfiguring方法中修改
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseSqlServer(/*连接字符串*/);
在project.json添加引用
"Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-rc2-final",
在OnConfiguring方法中修改
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
optionsBuilder.UseNpgsql(/*连接字符串*/);
码农,死宅前几天看了一个基于sqlserver的负载均衡与读写分离的软件Moebius,实现的方式还是不错的,这使得用sqlserver数据库的同学时有机会对数据库进行更有效的优化了
看着人有做的东西,自己也想用EF来实现一个读写分离,所以就有了本篇文章,仓储大叔读写分离的思路是:
1  用sqlserver自带的发布、订阅实现主,从数据库的结构,同步这事由sql帮我们完成
2  配置文件建立几个供只读的数据库连接串
3  建立SQL命令拦截器
4  修改大叔的DbContextRepository基数,添加拦截行为
5  测试,搞定
有了上面的想法,咱就可以干事了,第一步不用说了,可以自己百度,从第2步说起
2  配置文件建立几个供只读的数据库连接串
&!-- 只写--&
&add name="backgroundEntities" connectionString="metadata=res://*/background.csdl|res://*/background.ssdl|res://*/background.provider=System.Data.SqlCprovider connection string=&data source=.;initial catalog=persist security info=Tuser id=password=zzl123;multipleactiveresultsets=Tapplication name=EntityFramework&" providerName="System.Data.EntityClient" /&
&!-- 只读--&
&add name="backgroundEntitiesRead" connectionString="metadata=res://*/background.csdl|res://*/background.ssdl|res://*/background.provider=System.Data.SqlCprovider connection string=&data source=.;initial catalog=background_Read1;persist security info=Tuser id=password=zzl123;multipleactiveresultsets=Tapplication name=EntityFramework&" providerName="System.Data.EntityClient" /&
3  建立SQL命令拦截器
/// &summary&
/// SQL命令拦截器
/// &/summary&
public class NoLockInterceptor : DbCommandInterceptor
private static readonly Regex _tableAliasRegex =
new Regex(@"(?&tableAlias&AS \[Extent\d+\](?! WITH \(NOLOCK\)))",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
[ThreadStatic]
public static bool SuppressNoL
public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext&int& interceptionContext)
string conn = command.Connection.ConnectionS
base.NonQueryExecuting(command, interceptionContext);
public override void ScalarExecuting(DbCommand command,
DbCommandInterceptionContext&object& interceptionContext)
command.Connection.Close();
command.Connection.ConnectionString = "data source=.;initial catalog=background_Read1;persist security info=Tuser id=password=zzl123;multipleactiveresultsets=Tapplication name=EntityFramework";
command.Connection.Open();
if (!SuppressNoLock)
mandText =
_tableAliasRegex.mandText, "${tableAlias} WITH (NOLOCK)");
public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext&DbDataReader& interceptionContext)
command.Connection.Close();
command.Connection.ConnectionString = "data source=.;initial catalog=background_Read1;persist security info=Tuser id=password=zzl123;multipleactiveresultsets=Tapplication name=EntityFramework";
command.Connection.Open();
if (!SuppressNoLock)
mandText =
_tableAliasRegex.mandText, "${tableAlias} WITH (NOLOCK)");
4  修改大叔的DbContextRepository基数,添加拦截行为
public DbContextRepository(IUnitOfWork db, Action&string& logger)
UnitWork =
Db = (DbContext)
((IObjectContextAdapter)Db).mandTimeout = 0;
//SQL语句拦截器
System.Data.Entity.Infrastructure.Interception.DbInterception.Add(new EntityFrameworks.mon.NoLockInterceptor());
EntityFrameworks.mon.NoLockInterceptor.SuppressNoLock = true;
5  大功造成,感谢阅读!
本文章代码没有全部展示,只是展示一种思想,希望可以给大家带来帮助。
阅读(...) 评论()

我要回帖

更多关于 数据库读写分离实现 的文章

 

随机推荐