将 Entity Framework Core 迁移用于类库项目 [英] Using Entity Framework Core migrations for class library project

查看:30
本文介绍了将 Entity Framework Core 迁移用于类库项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个已经解决的问题,至少对于SQLite 数据库.

This seem to be an issue that have been fixed already, at least for the SQLite databases.

我的解决方案由 3 个项目组成:

My solution consists of 3 projects:

  1. WPF 项目(默认启动项目)(.NET Framework 4.7),
  2. 包含视图模型和非 UI 内容的核心"项目 - 类库项目 (.NET Standard 2.0)
  3. 关系"项目包含所有实体框架数据层 - 我喜欢将它们分开(.NET Standard 2.0)

我已将以下包安装到主 WPF 项目中:

I have installed the following packages into the main WPF project:

Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design

在我的主要 WPF 项目中引用了项目 2 和 3.所以基本上,EF 解决 DbContextes 应该就足够了.

Projects 2 and 3 are referenced in my main WPF project. So basically, it should be enough for the EF to resolve the DbContextes.

然而,它不是 - 因为在我的 WPF 项目上运行 Add-Migration 结果:

However, it's not - as running Add-Migration on my WPF project results in:

PM> Add-Migration "Initial"
No DbContext was found in assembly 'TestWPFProject'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.

在包管理器控制台中默认切换到项目 3 结果:

Switching to project 3 as default in the Package Manager Console results in:

PM> Add-Migration "Initial"
Unable to create an object of type 'ClientDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ClientDataStoreDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

如何在我的类库项目和 WPF 项目中正确使用 EF Core 迁移?

推荐答案

我复制了您的解决方案并找到了...一个解决方案 :)

I reproduced your solution and found... a solution :)

  1. 核心"项目 - 名为 ClassLibrary1
  2. 关系"项目 - 称为 EFClssLibrary
  3. WPF 应用项目 - 称为 WpfApp1

让我们深入.

名称:ClassLibrary1.

类型:.NET Standard 2.0 类库.

依赖项:无.

在我的测试解决方案中,它只包含一个类,一个名为 Person 的模型.

In my test solution, it contains only one class, a model called Person.

Person.cs

namespace ClassLibrary1
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }
}

<小时>

2.关系项目

名称:EFClassLibrary.

类型:.NET Standard 2.0 类库.

依赖关系:

在我的测试解决方案中,这个项目只包含一个类:数据库上下文.

This project, in my test solution, contains only one class: the database context.

ClientDbContext.cs

using ClassLibrary1;
using Microsoft.EntityFrameworkCore;

namespace EFClassLibrary
{
    public class ClientDbContext : DbContext
    {
        const string connectionString = "Server=(localdb)\mssqllocaldb;Database=ClientDb;Trusted_Connection=True;";

        public ClientDbContext() : base() { }

        public ClientDbContext(DbContextOptions<ClientDbContext> options) : base(options) { }

        public DbSet<Person> People { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(connectionString);
        }
    }
}

连接字符串

在这个类中定义了一个使用连接字符串连接到数据库(假设它是LocalDb SQL Server).如果要将连接字符串放在配置文件中,可以在解决方案中添加共享配置文件,然后在 App.config 文件中引用该文件(有关更多信息,请查看 App.configa href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings-and-configuration-files#using-external-configuration-files" rel="noreferrer">本页)

Connection string

In this class a defined an used the connection string to connect to the database (assuming it's LocalDb SQL Server). If you want to put the connection string in a config file, you could add a shared config file in your solution and then reference that file in your App.config file (for more informartion take a look at this page)

为了能够在此项目上添加迁移而不将其他项目设置为启动项目,您必须设置目标框架.右键单击该项目,然后单击Edit EFClassLibrary.csproj 条目.在 <TargetFramework>netstandard2.0</TargetFramework> 行下方,您应该添加另一行来指定要定位的框架.要以 .NET Framework 4.7 为目标,您应该添加

In order to be able to add migrations on this project without setting as startup project other projects, you must set the target framework. Right click on the project and click on the Edit EFClassLibrary.csproj entry. Below the <TargetFramework>netstandard2.0</TargetFramework> line, you should add another line which specify which framework you want to target. To target the .NET Framework 4.7 you should add

<TargetFramework>net47</TargetFramework>

可以找到所有允许值的列表这里.

A list of all allowed values can be found here.

在添加 .NET Framework 4.7 作为目标后,我的 EFClassLibrary.csproj 看起来像下面的代码.

My EFClassLibrary.csproj look like the code below after adding the .NET Framework 4.7 as target.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <TargetFramework>net47</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.1" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..ClassLibrary1ClassLibrary1.csproj" />
  </ItemGroup>

</Project>

添加迁移

现在您已准备好添加您的第一个迁移.打开包管理器控制台并将 EFClassLibrary 设置为默认项目.此外,将该项目设置为启动项目(右键单击该项目,然后单击设置为启动项目条目).

Adding migrations

Now you are ready to add your first migration. Open the Package Manager Console and set as default project the EFClassLibrary. Also, set that project as startup project (right-click on the project and click on the Set as startup project entry).

类型

PM> Add-Migration Initial

然后

PM> Update-Database

<小时>

3.WPF 应用项目

名称:WpfApp1.

类型:WPF 应用程序使用 .NET Framework 4.7.

依赖关系:

在这个项目中我没有添加任何文件.A 刚刚编辑了 MainWindow.xaml.cs 文件以检查一切是否正常.

In this project I added no files. A just edited the MainWindow.xaml.cs file to check that everything works correctly.

MainWindow.xaml.cs

using ClassLibrary1;
using EFClassLibrary;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var db = new ClientDbContext();

            db.People.Add(new Person()
            {
                Name = "Omar"
            });

            db.SaveChanges();
        }
    }
}

希望有帮助:)

这篇关于将 Entity Framework Core 迁移用于类库项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆