文章出處

Linux用的是Ubuntu,dnx版本是1.0.0-beta6-12120,EF版本是7.0.0-beta5。

以下是用Entity Framework 7生成SQL Server數據庫的操作步驟。

在project.json中添加Entity Framework 7的引用:

{
    "dependencies":{
        "EntityFramework.SqlServer": "7.0.0-beta5",
        "EntityFramework.Commands": "7.0.0-beta5"
    }
}

定義實體類,比如:

namespace CNBlogs.AboutUs.Models
{
    public class TabNav
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public string Url { get; set;}

        public bool IsActive { get; set; }
    }
}

定義DbContext,比如:

using Microsoft.Data.Entity;
using CNBlogs.AboutUs.Models;

namespace CNBlogs.AboutUs.Data
{
    public class EfDbContext : DbContext
    {
        public DbSet<TabNav> TabNavs { get; set; }
    }
}

在config.json中添加數據庫連接字符串:

{
    "Data": {
        "ConnectionString": "[數據庫連接字符串]"
    }
}

在Startup.cs中加載config.json中的配置:

public Startup(IApplicationEnvironment appEnv)
{
    Configuration = new Configuration(appEnv.ApplicationBasePath)
        .AddJsonFile("config.json");
}

public IConfiguration Configuration { get; set; }

注:

1)需要添加命令空間Microsoft.Framework.ConfigurationModel與Microsoft.Framework.Runtime;

2)當時由于沒有正確加載config.json,遇到了 No data stores are configured問題。

在Startup.cs中配置EF:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<EfDbContext>(options =>
        {
            options.UseSqlServer(Configuration.Get("Data:ConnectionString"));
        });
}

注:需要引用命名空間Microsoft.Data.Entity。

在project.json中添加ef command以使用EF的遷移功能生成數據庫。

{
    "commands":{
        "ef": "EntityFramework.Commands"
}

安裝所需要的包包:

dnu restore

用ef命令進行數據庫的生成:

dnx . ef migration add FirstMigration
dnx . ef migration apply

生成成功!

【遺留問題】

以上的操作是使用基于mono的dnx完成的,使用基于corelcr的dnx會出現下面的問題:

System.PlatformNotSupportedException: This platform does not support getting the current color.
   at System.ConsolePal.get_ForegroundColor()
   at Microsoft.Data.Entity.Commands.Utilities.ConsoleCommandLogger.WriteVerbose(String message)

這是由于corefx的ConsolePal.Unix.cs中沒有實現ForegroundColor屬性的get操作。

【遺留問題解決】

后來通過修改corefx中ConsolePal.Unix.cs的代碼,讓ForegroundColor返回一個默認顏色。然后將自己編譯出來的System.Console.dll復制到dnx-coreclr-linux-x64/bin/中臨時解決了問題。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()