频道栏目
首页 > 资讯 > asp > 正文

ASP.NET Core 1.0 使用 MySQL for EF Core 1.0

16-07-18        来源:[db:作者]  
收藏   我要投稿

经过多天的项目设计实践,本来都几乎放弃使用 MySQL 去使用 MSSQL ,但几经周折还是在国外找到了在 .NET Core 中使用 MySQL 数据库的方法(官方的进度不敢恭维,现使用的是第三方库),在此分享一下。

首先,要配置一下 NuGet 程序包源,因为该包暂时还没发布到 NuGet 库中。

程序包源:https://www.myget.org/F/pomelo/api/v2/

然后添加引用 Pomelo.EntityFrameworkCore.MySql ,使用 1.0.0 版本即可。(据消息该包会在八月初可以在 NuGet源中找到)

最后以往 Core First 该怎么用现在就怎么用。

以下附上我的示例:

 1 public void ConfigureServices(IServiceCollection services)
 2         {
 3 
 4             // Add framework services.
 5             services.AddMvc();
 6 
 7             services.AddDbContext(options => options.UseMySql(Option.EntityContextSql));
 8 
 9             services.Configure(option =>
10             {
11                 option.UseHttps(Path.Combine(new DirectoryInfo(Directory.GetCurrentDirectory()).FullName, "cret.pfx"), "pw");
12             });
13         }
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DB
{
    public class DBContext : DbContext
    {
        public DBContext(DbContextOptions options): base(options)
        {
        }

       //省略实体定义

        private static readonly IServiceProvider _serviceProvider = new ServiceCollection().AddEntityFrameworkMySql().BuildServiceProvider();
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseInternalServiceProvider(_serviceProvider).UseMySql(Option.EntityContextSql);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

    }
}
1         public static string EntityContextSql
2         {
3             get
4             {
5                 return string.Format("Data Source={0};port={1};user id={2};password={3};database={4};Charset=utf8;", EntityConfig.dataSource, EntityConfig.port, EntityConfig.id, EntityConfig.pw, EntityConfig.db);
6             }
7         }

 

相关TAG标签
上一篇:【备战面试之】五、谈扩展方法的理解
下一篇:C#获得枚举类型的长度
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站