asp.net mysql 读写分离_C#简单构架之EF进行读写分离+多数据库Mysql/SqlService

[导读]最近因为项目需要,研究了下EF的读写分离,所以做了一个demo进行测试,下面是项目的结构表现层view 主要提供Web、WebApi等表现层的解决方案公共层public 主要提供项目公共类库,数据缓存基础方法等实体层model 主要提供数据

最近因为项目需要,研究了下EF的读写分离,所以做了一个demo进行测试,下面是项目的结构

f2ccbc5cf7383fe9793e1b7e1a5ccbdd.png

表现层view

主要提供Web、WebApi等表现层的解决方案

公共层public

主要提供项目公共类库,数据缓存基础方法等

实体层model

主要提供数据库映射模型,还有就是DDD领域操作模型

数据层Db

主要封装EF操作基础类

数据服务层Service

主要提供数据库操作服务、缓存操作服务

数据接口服务层inface

主要提供数据库操作服务接口、缓存操作服务接口

1.首先是多数据库的支持,目前就支持mysql/sqlservice,如果需要添加更多的数据库支持,只需要再数据库操作类型上面添加即可/// 

/// 数据库类型

/// 

public enum DbContextType : byte

{

SqlService = 1,

MySql = 2

}

View Code

分别对mysql/sqlservice的上下文操作进行封装/// 

/// MySql操作类

/// 

[DbConfigurationType(typeof(MySqlEFConfiguration))]

public class MySqlContext : DbContext

{

public DbSet TestEntities { get; set; }

/// 

/// 配置默认的字符串链接

/// 

public MySqlContext() : base("DefaultConnection") {

}

/// 

/// 自定义数据库链接

/// 

/// 

public MySqlContext(string connenction) : base(connenction) { }

/// 

/// 实体对应规则的映射配置

/// 

/// 

protected override void OnModelCreating(DbModelBuilder modelBuilder)

{

}

}

View Code/// 

/// Sql数据库操作类

/// 

public class SqlServiceContext : DbContext

{

/// 

/// 配置默认的字符串链接

/// 

public SqlServiceContext() {

}

/// 

/// 自定义数据库链接

/// 

/// 

public SqlServiceContext(string connenction) : base(connenction) {

}

/// 

/// 实体对应规则的映射配置

/// 

/// 

protected override void OnModelCreating(DbModelBuilder modelBuilder)

{

}

}

View Code

在view调用时候,进行ef上下文初始化只需要设置类型/// 

/// 数据库策略初始化类

/// 

public static class DBInitializer

{

public static DbContextType DbContextType { get; set; }

/// 

/// 数据库初始化策略配置

/// `

public static void Initialize(DbContextType ContextType)

{

string IsUsedWR = System.Configuration.ConfigurationManager.AppSettings["IsUsedWR"];

DbContextType = ContextType;

///获得数据库最后一个版本

//   Database.SetInitializer(new MigrateDatabaseToLatestVersion());

if (ContextType == DbContextType.SqlService)

{

Database.SetInitializer(new MigrateDatabaseToLatestVersion());

if (IsUsedWR == "1") {

Database.SetInitializer(new MigrateDatabaseToLatestVersion());

}

else

{

Database.SetInitializer(null);

}

}

else

{

Database.SetInitializer(new MigrateDatabaseToLatestVersion());

if (IsUsedWR == "1")

{

Database.SetInitializer(new MigrateDatabaseToLatestVersion());

}

else

{

Database.SetInitializer(null);

}

//Database.SetInitializer(null);

// Database.SetInitializer(null);

}

// Database.SetInitializer(null);

///删除原来数据库 重新创建数据库

//Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

// Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

}

}

View Codepublic class MvcApplication : System.Web.HttpApplication

{

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes);

BundleConfig.RegisterBundles(BundleTable.Bundles);

//Autofac

//ContainerBuilder builder = new ContainerBuilder();

//builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());

//IContainer container = builder.Build();

//DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

//Autofac初始化过程

ContainerBuilder builder = new ContainerBuilder();

builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());//注册mvc容器的实现

var assemblys = BuildManager.GetReferencedAssemblies().Cast().ToList();

builder.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => t.Name.Contains("Service")).AsImplementedInterfaces();

var container = builder.Build();

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

//初始化数据库

DBInitializer.Initialize(DbContextType.MySql);

}

}

View Code

通过上面多数据库的支持已经完成,下面进行读写分离,分别进行继承上述上下文操作/// 

/// 读

/// 

public class WriteSqlServiceContext : SqlServiceContext

{

public WriteSqlServiceContext() : base("") { }

}

/// 

/// 写

/// 

public class ReadSqlServiceContext : SqlServiceContext

{

public ReadSqlServiceContext() : base("") { }

}

View Code

通过工厂类进行初始化

0be6dab1c6390cbd54865625d75e9a50.gif

6b107953289b257e66658888177b4e0d.gif/// 

/// 上下文工厂类

/// 

public static class Contextfactory

{

/// 

/// 获取上下文

/// 

/// 

public  static DbContext GetContext(DbOpertionType OpertionType)

{

DbContextType ContextType = DBInitializer.DbContextType;

if (ContextType == DbContextType.MySql)

{

if (OpertionType == DbOpertionType.Read)

return new ReadMySqlContext();

else

return new WriteMySqlContext();

}

else

{

if (OpertionType == DbOpertionType.Read)

return new ReadSqlServiceContext();

else

return new WriteSqlServiceContext();

}

}

/// 

/// 获取上下文操作

/// 

/// 

/// 

/// 

public static TEntity CallContext(DbOpertionType OpertionType) where TEntity: DbContext

{

var DbContext = GetContext(OpertionType);

return (TEntity)DbContext;

}

}

View Code

最后配置webcofig即可

View Code

最后进行测试public class TestController : Controller

{

private ITestService _TestServiceDb { get; set; }

public TestController(ITestService TestServiceDb) {

_TestServiceDb = TestServiceDb;

}

// GET: Test

public ActionResult Index()

{

var result = _TestServiceDb.AddEntity(new Test() { ID=Guid.NewGuid(), Age=11, CreateTime=DateTime.Now, Name="Test" });

var NewResult = _TestServiceDb.GetEntityByID(result.ID);

return View();

}

}

View Code

bfd8f715a7a413daba31828ded040acd.png

搞定,可能在代码上有点累赘,但是总算是可行的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值