为 .NET Core 项目添加 EntityFrameworkCore 支持






4.90/5 (9投票s)
演示如何在 .NET Core 项目中添加 EF 支持
引言
我每天都使用 EntityFramework,但我不是每天都向现有项目添加 EntityFramework (EF)。我必须一遍又一遍地创建新项目或向现有项目添加 EntityFramework,于是我决定记录下这些步骤。
在本文中,我将展示如何开始使用 EntityFramework。我将从一个没有 EntityFramework 支持的项目开始,然后向该项目添加 EF 支持,并使用迁移来更新数据库。我使用的是 Visual Studio 2017、带 SQL Server Management Studio 的 MS SQL Server 以及 .NET Core SDK 2.2 的 EntityFrameworkCore。
本文相关的代码可在 GitHub 上找到。
创建解决方案和项目
我首先在 Visual Studio 中创建了一个空的解决方案,并添加了一个面向 .NET Core 2.2 的 WebAPI 项目。
我使用的是 MS SQL Server,因此我正在通过 Nuget 包管理器为 EntityFramework 查找 'Microsoft.EntityFrameworkCore.SqlServer
'。
右键单击项目,然后单击“管理 NuGet 程序包”,并选择当前最新的稳定版本 2.2.6。
我将使用代码优先迁移,因此我还需要添加 'Microsoft.EntityFrameworkCore.Design
' 的引用。
我将更新 appsetting.json 文件以配置连接字符串。我使用的是本地可用的 MS SQLServer。我将连接命名为 'DefaultConnection
',数据库名称为 'ApplicationDb
'。我将通过添加以下内容来更新 appsetting.json 文件:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;
Database=ApplicationDb;Trusted_Connection=True;"
}
配置数据库和模型
我将把与 Entity Framework 相关的代码组织在一个单独的文件夹中。因此,我在项目中添加了一个名为 'DBContext' 的文件夹。接下来,我将使用代码优先方法向数据库添加表。
我将添加三个表,分别是 Customer
、Contact
和 CustomerContact
。代码示例显示了两个额外的类:IAuditable
和 Audit
。Audit
表用于存储所有表中发生的更改历史记录,而 IAuditable
是一个接口,用于统一 Auditable
属性。这些是为附加工作准备的,目前可以忽略。有许多 Enum
用于为客户数据提供类型信息。Customer
和 Contact
实体之间存在多对多关系,因此我添加了 CustomerContact
实体来存储这种关系。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AutotrackEntityChange.DBContext
{
public class Customer : IAuditable
{
public Guid Id { get; set; }
public String AccountNumber { get; set; }
public String Name { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public String LastModifiedBy { get; set; }
public bool IsInactive { get; set; }
public ICollection<CustomerContact> CustomerContacts { get; set; }
}
public class Contact : IAuditable
{
public Guid Id { get; set; }
public String Name { get; set; }
public String Title { get; set; }
public String Phone { get; set; }
public String Email { get; set; }
public ContactTypeEnum ContactType { get; set; }
public String Note { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public String LastModifiedBy { get; set; }
public bool IsInactive { get; set; }
public ICollection<CustomerContact> CustomerContacts { get; set; }
}
public class CustomerContact:IAuditable
{
public Guid Id { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public string LastModifiedBy { get; set; }
public bool IsInactive { get; set; }
public Guid CustomerId { get; set; }
public Customer Customer { get; set; }
public Guid ContactId { get; set; }
public Contact Contact { get; set; }
}
public class Audit
{
public Guid Id { get; set; }
public Guid? EntityId { get; set; }
public string User { get; set; }
public String Entity { get; set; }
public DateTime DateTime { get; set; }
public string ColumnName { get; set; }
public String OldValue { get; set; }
public String NewValue { get; set; }
public EntityStateChangeTypeEnum ChangeType { get; set; }
}
/// <summary>
/// This interface determines what will be automatically tracked.
/// </summary>
interface IAuditable
{
Guid Id { get; set; }
DateTime? CreatedDate { get; set; }
DateTime? ModifiedDate { get; set; }
String LastModifiedBy { get; set; }
bool IsInactive { get; set; }
}
public enum EntityStateChangeTypeEnum
{
Added,
Deleted,
Modified,
}
public enum ContactTypeEnum
{
Primary,
Secondary,
Emergency,
}
}
有了这些,我们就准备好添加模型了。我创建了一个名为 'ApplicationDbContext
' 的类,该类继承自 'DbContext
' 以配置 EntityFramework。在此类中,我首先将所有三个表定义为 DbSet
,并添加一个 public
构造函数来将 DbContext
连接到数据库。
using Microsoft.EntityFrameworkCore;
namespace AutotrackEntityChange.DBContext
{
public class ApplicationDbContext: DbContext
{
//Define DbSets
public DbSet<Customer> Customers { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<CustomerContact> CustomerContacts { get; set; }
public DbSet<Audit> Audits { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) {}
}
}
由于我使用的是 SQLServer,因此我在 startup 类中的 ConfigureServices
中添加了 sqlserver
选项,并引用了上面创建的 'ApplicationDbContext
'。
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
添加迁移并更新数据库
完成上述更改后,我就可以使用 entity framework 创建迁移了。在 Visual Studio 的程序包管理器控制台中,运行以下命令:
Add-Migration InitialCreate
命令运行后,迁移已创建。这在解决方案资源管理器中是可见的。迁移文件夹包含迁移文件和设计文件。这些文件的内容可以在代码存储库中查看。简而言之,迁移是数据库的指令,在本例中,用于创建表和关系。
现在已经添加了迁移,我可以更新数据库以便应用迁移。为此,请在程序包管理器控制台中运行以下命令:
Update-database
当上述命令运行时,它会在配置的数据库中创建迁移中定义的表和任何更新。此时,我可以在 SSMS 中查看 ApplicationDb
数据库中的这些表。
摘要
在本文中,我提供了一个分步方法,用于将 EntityFramework 代码优先方法添加到 .NET Core 项目。由于我并不总是每天都向项目添加 EntityFramework
,因此这些步骤很难记住,并且需要仔细执行。我使用了 WebAPI 项目的示例,但这些步骤同样适用于 MVC 或类库项目。最后,我使用了 MS SQL Server 作为数据库。但是,根据需要,这些步骤可以用于连接其他数据库,只需进行少量配置更改。我希望这能对您有所帮助,并欢迎您提出评论和建议。
参考文献
历史
- 2019 年 8 月 8 日:初始版本