.NET跨平台:在Linux上基于ASP.NET 5用EF7生成数据库

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/中临时解决了问题。

posted @ 2015-07-05 11:55  dudu  阅读(2988)  评论(5编辑  收藏  举报