CodeFirst+MySQL+.Net Core配置詳情

EF 基礎操做:http://www.cnblogs.com/M-LittleBird/p/5852395.htmlhtml

1、使用CodeFirst模式

     一、在須要添加的項目上右鍵點擊選擇添加ADD.NET 實體數據模型。mysql

二、選擇模型內容,選擇CodeFirst模型,選擇本身須要的類型,這裏我選擇空的CodeFirst模型sql

三、選擇模型後再當前項目中生成 會默認引用 ef 相關 dll,還須要添加mysql相關dll,使用NuGet 安裝mysql數據庫

 

添加成功後再項目中會生成如下兩個文件json

四、修改App.config中的 數據庫鏈接字符串app

mysqlide

<connectionStrings>
    <add name="MyContext" connectionString="server=127.0.0.1;user id=root;password=;persistsecurityinfo=True;database=schedule" 
     providerName="MySql.Data.MySqlClient" />
</connectionStrings>

sql serverspa

<connectionStrings>
    <add name="MyContext" connectionString="Data Source=.;Initial Catalog=xxxx;Persist Security Info=True;User ID=xx;Password=xxx;Connect Timeout=120;" 
     providerName="System.Data.SqlClient" />
</connectionStrings>

五、重名名 Model1 爲 MyContext 並修改內容,修改以下3d

namespace BooksStore.Domain
{
    using MySql.Data.Entity;
    using System;
    using System.Data.Entity;
    using System.Linq;


    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class MyContext : DbContext
    {
        //您的上下文已配置爲從您的應用程序的配置文件(App.config 或 Web.config)
        //使用「Model1」鏈接字符串。默認狀況下,此鏈接字符串針對您的 LocalDb 實例上的
        //「BooksStore.Domain.Model1」數據庫。
        // 
        //若是您想要針對其餘數據庫和/或數據庫提供程序,請在應用程序配置文件中修改「Model1」
        //鏈接字符串。
        public MyContext()
            : base("name=MyContext")
        {
        }

        //爲您要在模型中包含的每種實體類型都添加 DbSet。有關配置和使用 Code First  模型
        //的詳細信息,請參閱 http://go.microsoft.com/fwlink/?LinkId=390109//這是示例 改成本身的實體類
        public virtual DbSet<MyEntity> MyEntities { get; set; }
    }
    //這是示例 改成本身的實體類
    public class MyEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

 注:實例類名稱建議同數據庫表名保持一致,這裏默認把類名看成數據庫表名。code

ASP.NET CORE 中配置

直接複製上面的MyContext類到core項目中。

使用NuGet添加包:Pomelo.EntityFrameworkCore.MySql。

Startup類中註冊服務,修改以下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    //註冊mysql服務
    services.AddDbContext<SMContext>(options => options.UseMySql(Configuration["ConnectionStrings:DefaultConnection"]));
}

appsettings.json中添加數據庫字符串配置,配置以下:

{
  "ConnectionStrings": {
    "DefaultConnection": "server=127.0.0.1;user id=root;password=123456;persistsecurityinfo=True;database=schedule",
    "DotNetCoreConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
相關文章
相關標籤/搜索