entity-framework - .net core - WebApp 和 EF 数据层的分离不起作用

标签 entity-framework ef-code-first asp.net-core database-migration

我正在尝试在.net core 中创建一个新项目。我希望在我的数据项目中包含所有与 EF 相关的内容,如下所示:

Solution
-- Project.Data
-- Project.WebApp
-- Project.AnotherWebApp

不幸的是,我收到以下错误:

当尝试在数据项目上运行迁移(dotnet ef migrations add init)时,我收到此错误:

Could not invoke this command on the startup project 'MyProject.Data'. This preview of Entity Framework tools does not support commands on class library projects in ASP.NET Core and .NET Core applications. See http://go.microsoft.com/fwlink/?LinkId=798221 for details and workarounds.

不幸的是,链接中解释的两种解决方法都不起作用。

另一方面,当在 WebApp 上运行迁移命令时,我收到此错误: 您的目标项目“MyProject.Portal”与您的迁移程序集“MyProject.Data”不匹配。更改您的目标项目或更改您的迁移程序集。

Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("MyProject.Portal")). By default, the migrations assembly is the assembly containing the DbContext. Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project.

我怎样才能让它工作,理想情况下这样我就可以在数据项目上运行迁移?!

非常感谢您的帮助, 尼克

最佳答案

How can I get this to work, ideally so that I can run the migrations on the Data project?!

Entity Framework Core 目前不支持在类库上运行迁移,因为迁移需要应用程序。以下解决方法创建一个只有一项作业的应用程序:运行迁移。

Here is a GitHub sample project .

数据层

这是一个非常简单的数据层,包含上下文和一个简单的实体。

数据层/MyContext.cs

using Microsoft.EntityFrameworkCore;

namespace DataLayer
{
    public class MyDataModel 
    {
        public Guid Id { get; set; }
    }

    public class MyContext : DbContext
    {
        public MyContext(DbContextOptions<MyContext> options)
            : base(options)
        {
        }

        public DbSet<MyDataModel> MyDataModels { get; set; }
    }
}

数据层/project.json

{
    "version": "1.0.0-*",
    "dependencies": {
        "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
        "NETStandard.Library": "1.6.0"
    },
    "frameworks": {
        "netstandard1.6": {}
    }
}

数据层迁移应用程序

这个小程序运行迁移。

我们从该项目的目录运行 dotnet ef 迁移...dotnet ef 数据库...。这两个命令在创建迁移和更新数据库时都使用 ConfigureServices

运行迁移或更新不需要Configure方法。相反,它只是让我们使用 dotnet run 对数据库进行测试读取。

Datalayer.Migrations/Program.cs

using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using DataLayer;

namespace DataLayer.Migrations
{
    public class Program
    {
        private readonly IConfigurationRoot _configuration;

        public Program()
        {
            _configuration = new ConfigurationBuilder()
                .AddJsonFile($"appsettings.json")
                .Build();
        }

        public static void Main(string[] args)
        {
            new WebHostBuilder()
                .UseKestrel()
                .UseStartup<Program>()
                .Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {   
            var currentAssembly = "DataLayer.Migrations";
            var connectionString = 
                _configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext<MyContext>(optionsBuilder =>
            {
                optionsBuilder.UseSqlite(
                    connectionString,
                    builder => builder.MigrationsAssembly(currentAssembly));
            });
        }

        public void Configure(MyContext context)
        {    
            var data = new MyDataModel
            {
                Id = System.Guid.NewGuid()
            };

            context.Add(data);
            context.SaveChanges();

            var count = context.MyDataModels.CountAsync().Result;
            Console.WriteLine($"There are {count} items.");
        }
    }
}

Datalayer.Migrations/appsettings.json

{
    "ConnectionStrings": {
        "DefaultConnection": 
            "Filename=MyDatabase.sqlite"
    }
}

Datalayer.Migrations/project.json

{
    "version": "1.0.0-*",
    "buildOptions": {
        "emitEntryPoint": true,
        "copyToOutput": {
            "include": [
                "appsettings.json"
            ]
        }
    },
    "dependencies": {
        "DataLayer": "1.0.0-*",
        "Microsoft.AspNetCore.Hosting": "1.0.0",
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
        "Microsoft.Extensions.Configuration.Json": "1.0.0-*",
        "Microsoft.EntityFrameworkCore.Sqlite": "1.0.0",
        "Microsoft.EntityFrameworkCore.Design": {
            "type": "build",
            "version": "1.0.0-preview2-final"
        }
    },
    "tools": {
        "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
    },
    "frameworks": {
        "netcoreapp1.0": {
            "dependencies": {
                "Microsoft.NETCore.App": {
                    "type": "platform",
                    "version": "1.0.1"
                }
            }
        }
    }
}

关于entity-framework - .net core - WebApp 和 EF 数据层的分离不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474883/

相关文章:

c# - 使用 Entity Framework 6 代码优先注释映射 xmltype oracle

c# - Entity Framework ,更新相关对象时出现问题

c# - ASP.NET 核心 : Idle timeout between the calls with a delay

c# - 将多个文件提交给接受 ICollection<IFormFile> 的 ASP.NET Controller

sql - 使用Lambda表达式检查字符串值是否包含任何数字

c# - EF4.1 代码优先 : How to disable delete cascade for a relationship without navigation property in dependent entity

c# - Entity Framework 6 - 缺少仅包含引用不同表的主键的表

c# - 如何在 ASP.Net 5 中删除文件

c# - Entity Framework Core 单个对象而不是列表

c# - 模拟 DbContext.set<T>.Add() EF6