自学内容网 自学内容网

轻松学EntityFramework Core--模型创建

一、使用代码优先(Code-First)创建模型

Code-First 方法是 EF Core 提供的一种用于定义模型的方式,它允许开发人员通过编写 C# 类来定义数据库模式,再通过迁移命令生成数据库表。下面我们来一起看一下代码优先如何使用。

1.1、创建项目并安装 EF Core

首先,创建一个新的 .NET 项目并安装 EF Core 包:

dotnet new console -n EFCoreCodeFirst
cd EFCoreCodeFirst
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
1.2、 定义模型类

接下来我们来定义一个博客系统的两个实体类 BlogPost

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

在这两个类中,我们看 Blog 类中存在 Post 类的 List 集合, Post 类中存在 Blog 类的实例和, Blog 实例的Id。具体它们的作用是什么,我们会在关系映射这一节详细讲解,在这里我们只需要知道这三个属性表示了 BlogPost 的关系即可。

2.3、 创建上下文类

接下来我们定义一个派生自 DbContext 的上下文类,它代表与数据库的会话,并且允许查询和保存数据。上下文类包含 DbSet<TEntity> 属性,表示数据库中的表。

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=BloggingDB;Trusted_Connection=True;");
    }
}

在上面的代码中 BloggingContext 类继承自 DbContext,它定义了与数据库交互的上下文。DbSet<Blog> BlogsDbSet<Post> Posts 是 DbSet 属性,分别代表数据库中的 Blog 和 Post 实体集合。DbSet 是一个用于查询和保存数据库中实体集合的集合。OnConfiguring 方法被重写,用来配置数据库上下文的数据库提供者和连接字符串,在这个例子中,它配置了使用SQL Server作为数据库提供者,并提供了一个连接字符串,指向名为 BloggingDB 的本地数据库。

2.4、 创建数据库

OK!模型定义完了,上下文类也创建了,现在我们就使用迁移命令来创建数据库。
首先,初始化迁移:

dotnet ef migrations add InitialCreate

初始化迁移完成后,会生成一个 Migrations 文件夹,它包含创建数据库的代码。
然后,更新数据库以应用迁移:

dotnet ef database update

迁移完成后,数据库及其表将会创建完成。
在这里插入图片描述
我们从数据库中看到,除了我们要创建的Blogs和Posts表外,还多了一张__EFMigrationsHistory表,__EFMigrationsHistory是一个特殊的表,它用于跟踪数据库模式的变更历史。当使用Entity Framework Core的迁移功能时,每次应用迁移(migration)到数据库时,迁移的元数据就会被记录在这个表中。__EFMigrationsHistory 表通常由Entity Framework Core自动创建和管理,开发者不需要手动操作这个表。表的结构如下:

  • MigrationId:唯一标识一个迁移的字符串。
  • ProductVersion:应用迁移时使用的Entity Framework Core的版本。

总结起来 __EFMigrationsHistory 表的作用有如下5点:

  1. 迁移跟踪:它记录了哪些迁移已经被应用到数据库上。这允许Entity Framework Core知道当前数据库的模式状态,并确定哪些迁移需要被应用或回滚。
  2. 版本控制:表中的记录提供了数据库模式的版本历史,这有助于团队协作和数据库模式的版本控制。
  3. 迁移应用顺序:__EFMigrationsHistory 表中的记录通常包含迁移名称和应用时间戳,这有助于了解迁移的顺序和时间。
  4. 回滚支持:如果需要回滚到之前的数据库模式状态,Entity Framework Core可以使用这个表来确定哪些迁移需要被撤销。
  5. 避免重复应用:由于迁移的元数据被记录在这个表中,Entity Framework Core可以避免重复应用相同的迁移,确保数据库模式的一致性。
2.5、 使用上下文类

现在,我们可以在代码中使用上下文类来操作数据库了:

class Program
{
    static void Main(string[] args)
    {
        using (var db = new BloggingContext())
        {
            // 创建并保存新的博客
            var blog = new Blog { Url = "http://sample.com" };
            db.Blogs.Add(blog);
            db.SaveChanges();

            // 查询并显示所有博客
            var blogs = db.Blogs.ToList();
            foreach (var b in blogs)
            {
                Console.WriteLine($"BlogId: {b.BlogId}, Url: {b.Url}");
            }
        }
    }
}

在上面的代码中,我们创建数据库上下文实例,使用 using 语句创建了 BloggingContext 的实例。然后我们创建了一个新的 Blog 实例,并设置其 Url 属性,并使用 Add 方法将其添加到 Blogs 集合中。最后调用 SaveChanges 方法将更改保存到数据库中。
在这里插入图片描述
接下来使用 ToList 方法查询数据库中的所有博客,并将其存储在 blogs 变量中。最后使用 foreach 循环遍历 blogs 集合,并打印每个博客的 BlogIdUrl

1.6、 完整示例代码

以下是完整的示例代码:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=BloggingDB;Trusted_Connection=True;");
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (var db = new BloggingContext())
        {
            // 创建并保存新的博客
            var blog = new Blog { Url = "http://sample.com" };
            db.Blogs.Add(blog);
            db.SaveChanges();

            // 查询并显示所有博客
            var blogs = db.Blogs.ToList();
            foreach (var b in blogs)
            {
                Console.WriteLine($"BlogId: {b.BlogId}, Url: {b.Url}");
            }
        }
    }
}

通过上述步骤,我们已经成功使用 Code-First 方法创建并使用了一个简单的 EF Core 模型。我们可以根据需要扩展模型和上下文类,以实现更复杂的数据库操作。

二、使用数据库优先(Database-First)创建模型

在 Entity Framework Core 中,Database-First 方法允许我们从现有的数据库生成模型。这通常用于我们已经有一个数据库并希望生成与其结构对应的实体类和上下文类。

2.1、 生成模型

使用 dotnet ef dbcontext scaffold 命令从现有数据库生成模型。需要提供连接字符串和数据库提供程序:

dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=BloggingDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

这个命令将连接到名为 BloggingDB 的数据库,并生成包含模型和上下文类的 Models 文件夹。生成完成我们就可以解决方案中看到生成的数据库模型类和数据库链接上下文。
在这里插入图片描述

2.2、 使用生成的模型

在生成模型后,我们可以在代码中使用上下文类和实体类。例如:

using System;
using System.Linq;
using EFCoreDatabaseFirst.Models;

class Program
{
    static void Main(string[] args)
    {
        using (var db = new BloggingDbContext())
{
    // 查询并显示所有表中的数据
    var items = db.Blogs.ToList(); 
    foreach (var item in items)
    {
        Console.WriteLine($"Id: {item.BlogId}, Url: {item.Url}");
    }
}
    }
}
2.3、生成代码示例
  1. Blog 实体类
namespace EFCoreDatabaseFirst.Models;

public partial class Blog
{
    public int BlogId { get; set; }

    public string Url { get; set; } = null!;

    public virtual ICollection<Post> Posts { get; set; } = new List<Post>();
}
  1. Post 实体类
namespace EFCoreDatabaseFirst.Models;

public partial class Post
{
    public int PostId { get; set; }

    public string Title { get; set; } = null!;

    public string Content { get; set; } = null!;

    public int BlogId { get; set; }

    public virtual Blog Blog { get; set; } = null!;
}
  1. 上下文类
namespace EFCoreDatabaseFirst.Models;

public partial class BloggingDbContext : DbContext
{
    public BloggingDbContext()
    {
    }

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

    public virtual DbSet<Blog> Blogs { get; set; }

    public virtual DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see https://go.microsoft.com/fwlink/?LinkId=723263.
        => optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BloggingDB;Trusted_Connection=True;");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>(entity =>
        {
            entity.HasIndex(e => e.BlogId, "IX_Posts_BlogId");

            entity.HasOne(d => d.Blog).WithMany(p => p.Posts).HasForeignKey(d => d.BlogId);
        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

通过上述步骤,我们可以使用 Database-First 方法从现有数据库生成 EF Core 模型,并在代码中使用生成的模型类和上下文类。这种方法特别适合已有数据库架构并希望快速生成数据访问代码的场景。

三、总结

在 Entity Framework Core 中,Code-First 方法允许开发人员通过编写 C# 类定义数据库模式,并使用迁移命令生成数据库表。首先,创建一个新的 .NET 项目并安装 EF Core 包。接着,定义模型类,如博客系统的 BlogPost 实体类,分别表示博客和博客文章,关联关系通过属性表示。在此基础上,创建上下文类 BloggingContext,该类继承自 DbContext,包含 DbSet<TEntity> 属性,表示数据库中的表,并配置数据库连接字符串。使用 dotnet ef migrations add InitialCreate 命令生成数据库迁移文件,随后通过 dotnet ef database update 应用迁移并创建数据库。最终,通过代码使用上下文类 BloggingContext 操作数据库,创建并保存新的博客数据,并查询显示所有博客。
Database-First 方法适用于从现有数据库生成模型。在创建项目并安装 EF Core 包后,使用 dotnet ef dbcontext scaffold 命令从数据库生成模型类和上下文类,指定连接字符串和数据库提供程序。生成的模型类和上下文类在代码中使用,以操作数据库。以博客系统为例,通过 BlogPost 实体类及其上下文类 BloggingDbContext,实现数据库的查询和数据操作。Database-First 方法特别适合已有数据库架构的场景,便于快速生成与数据库结构对应的数据访问代码。
这两种方法各有优劣,Code-First 适用于从零开始设计数据库结构,而 Database-First 适用于已有数据库的项目,开发者可根据具体需求选择合适的方法。


原文地址:https://blog.csdn.net/gangzhucoll/article/details/140730092

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!