目录

介绍

创建解决方案和项目

配置数据库和模型

添加迁移和更新数据库

总结

参考


介绍

我每天都在使用EntityFramework,但我不会每天向现有项目添加EntityFramework(EF)。我必须一次又一次地创建一个新项目或将EntityFramework添加到现有项目中,我决定记录这些步骤。

在本文中,我将展示如何开始使用EntityFramework。我将从一个不支持EntityFramework的项目开始,并将EF支持添加到项目中,并使用迁移来更新数据库。我使用Visual Studio 2017,MS SQL Server与SQL Server Management Studio和EntityFrameworkCore与.NET Core SDK 2.2。

GitHub上提供了与本文相关的代码。

创建解决方案和项目

我首先在Visual Studio中创建了一个空解决方案,并添加了一个WebAPI项目目标.NET Core 2.2。

Rn引用ios的framework_数据库

我正在使用MS SQL Server,因此我正在使用EntityFramework的Nuget包寻找'Microsoft.EntityFrameworkCore.SqlServer'。

右键单击该项目,然后单击“Manage NuGet Package”并选择当前为2.2.6的最新稳定版本。

Rn引用ios的framework_Core_02

我将使用代码优先迁移,因此,我也添加了对'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,我在启动类的ConfigureServices中添加了sqlserver选项,引用了上面创建的'ApplicationDbContext'。

services.AddDbContext<ApplicationDbContext>(options =>
	options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

添加迁移和更新数据库

通过以上这些更改,我准备使用实体框架创建迁移。在Visual Studio的包管理器控制台中,运行以下命令:

Add-Migration InitialCreate

Rn引用ios的framework_Rn引用ios的framework_03

命令运行后,已创建迁移。这在解决方案资源管理器中很明显。迁移文件夹包含迁移文件和设计文件。可以在代码存储库中查看这些内容。简而言之,迁移是数据库的指令,在此示例中,用于创建表和关系。

Rn引用ios的framework_EntityFrameworkCore_04

现在已添加迁移,我可以更新数据库以便可以应用迁移。为此,请在程序包管理器控制台中运行以下命令:

Update-database

运行上述命令时,它会创建表以及迁移到已配置数据库中定义的任何更新。这时,我可以在ApplicationDb数据库中查看我的SSMS中的那些表。

Rn引用ios的framework_数据库_05

总结

在本文中,我提供了一种逐步的方法来向.NET Core项目添加EntityFramework Code-First方法。因为我不一定每天都在添加EntityFramework项目,所以这些步骤很难记住,这些步骤需要谨慎执行。我使用了WebAPI项目的示例,但这些步骤同样适用于MVC或库项目。最后,我使用MS SQL Server作为数据库。但根据需要,这些步骤可用于连接其他数据库,只需对配置进行微小更改。我希望这会对某人有所帮助,我欢迎提出意见和建议。