在本教程中,你将创建一个 .NET Core 控制台应用,该应用使用 Entity Framework Core 对 SQLite 数据库执行数据访问。
可以通过在 Windows 上使用 Visual Studio,或在 Windows、macOS 或 Linux 上使用 .NET CLI,来完成本教程的操作。
先决条件
安装以下软件:
创建新项目
dotnet new console -o EFGetStarted
cd EFGetStarted
安装 Entity Framework Core
要安装 EF Core,请安装你所需的 EF Core 数据库提供程序的包。 本教程使用 SQLite,因为它在 .NET 支持的所有平台上运行。 有关可用提供程序的列表,请参阅 数据库提供程序。
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
创建模型
定义构成模型的上下文类和实体类。
- 在项目目录中,使用以下代码创建Model.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public string DbPath { get; }
public BloggingContext()
{
var folder = Environment.SpecialFolder.LocalApplicationData;
var path = Environment.GetFolderPath(folder);
DbPath = System.IO.Path.Join(path, "blogging.db");
}
// The following configures EF to create a Sqlite database file in the
// special "local" folder for your platform.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite($"Data Source={DbPath}");
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; } = new();
}
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; }
}
EF Core 还可以从现有数据库 反向工程 模型。
提示:为了清楚起见,此应用程序有意保持简单。 不应将连接字符串 存储在生产应用程序的代码中。 可能还需要将每个 C# 类拆分为自己的文件。
创建数据库
以下步骤使用 迁移 来创建数据库。
运行以下命令:
dotnet tool install --global dotnet-ef dotnet add package Microsoft.EntityFrameworkCore.Design dotnet ef migrations add InitialCreate dotnet ef database update
这将安装 dotnet ef 和在项目上运行命令所需的设计包。 该
migrations
命令为迁移搭建基架,为模型创建初始表集。 该database update
命令将创建数据库,并将新的迁移应用到该数据库。
创建、读取、更新 & 删除
打开 Program.cs ,并将内容替换为以下代码:
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using var db = new BloggingContext(); // Note: This sample requires the database to be created before running. Console.WriteLine($"Database path: {db.DbPath}."); // Create Console.WriteLine("Inserting a new blog"); db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" }); await db.SaveChangesAsync(); // Read Console.WriteLine("Querying for a blog"); var blog = await db.Blogs .OrderBy(b => b.BlogId) .FirstAsync(); // Update Console.WriteLine("Updating the blog and adding a post"); blog.Url = "https://devblogs.microsoft.com/dotnet"; blog.Posts.Add( new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" }); await db.SaveChangesAsync(); // Delete Console.WriteLine("Delete the blog"); db.Remove(blog); await db.SaveChangesAsync();
运行应用
dotnet run
后续步骤
- 按照 ASP.NET Core 教程 在 Web 应用程序中使用 EF Core
- 详细了解 LINQ 查询表达式
- 配置模型以指定所需长度和最大长度等内容
- 更改模型后,使用 迁移 更新数据库架构