第4章 4.2 Entity Framework Core基础 EF Core 入门

本节介绍EF Core的基本用法及注意事项

4.2.1 该选择什么数据库

EF Core 支持所有主流的数据库。

本书介绍的是SQL Server ,因为是微软亲儿子,所以EF CoreSQL Server的支持非常全面。

4.2.2 EF Core环境搭建

1. 安装Microsoft.EntityFrameworkCore.SqlServer

2. 创建【Book】实体类和这个实体类的配置类

 public class   Book
 {
     public long ID { get; set; }//主键
     public string  Title { get; set; }//标题
     public DateTime PubTime { get; set; }//发布日期

     public double Price { get; set; }//单价
     public string AuthorName { get; set; }//作者
 }
class BookEntityConfig : IEntityTypeConfiguration<Book>
{
    public void Configure(EntityTypeBuilder<Book> builder)
    {
        builder.ToTable("T_Books");
        builder.Property(e=>e.Title ).HasMaxLength(50).IsRequired();
        builder.Property(e => e.AuthorName).HasMaxLength(20).IsRequired();
    }
}

3. 创建测试类TestDbContext

//这里定义了一个名为TestDbContext的类,并且指定这个类继承自DbContext。
//这意味着TestDbContext可以使用Entity Framework Core提供的所有功能,用于与数据库进行交互。
class TestDbContext :DbContext
{
    public DbSet<Book> Books { get; set; }
    //这个方法用于配置数据库连接。
    //DbContextOptionsBuilder用于创建和配置DbContext的选项,通常包括数据库提供者和连接字符串。
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        string connStr = "Server=.;DataBase=demo1;Trusted_Connection=True";
        optionsBuilder.UseSqlServer(connStr);
    }
    //这个方法用于配置实体模型。ModelBuilder对象用于定义实体类与数据库表之间的映射。
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(this.GetType ().Assembly);
    }
}

4. 模型驱动开发:从实体类的定义中自动生成数据库表

安装NuGet包:Microsoft.EntityFrameworkCore.Tools

5. 在程序包管理器控制台执行命令:Add-Migration InitialCreate

控制台窗口在这儿打开:

执行结果:书中解释,这一步就是根据实体类及配置生成操作数据库的迁移代码

此时,可以在项目的Migrations文件夹中看到_InitialCreate文件,执行这段代码应用到数据库

/// <inheritdoc />
public partial class InitialCreate : Migration
{
    /// <inheritdoc />
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "T_Books",
            columns: table => new
            {
                ID = table.Column<long>(type: "bigint", nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Title = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
                PubTime = table.Column<DateTime>(type: "datetime2", nullable: false),
                Price = table.Column<double>(type: "float", nullable: false),
                AuthorName = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_T_Books", x => x.ID);
            });
    }

    /// <inheritdoc />
    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "T_Books");
    }
}

6. 执行命令:UpDate-Database

执行过程可能会报错误:

需要在连接字串里面加证书信任属性

执行成功:

然后检查数据库是否生成成功:

4.2.3 插入数据

balabala,TestDbContext类中的Books对应数据库中的T_Books表,操作Books就是操作数据库表,当然,操作完需要保存修改操作。用异步,提高并发处理能力。

插入数据代码如下:

using (TestDbContext testDBBook = new TestDbContext())
{
    var book1 = new Book { AuthorName = "于蛋", Title = "磨", Price = 5, PubTime = new DateTime(2099, 8, 15) };
    var book2 = new Book { AuthorName = "于蛋", Title = "舌尖上的足疗", Price = 250, PubTime = new DateTime(2099, 8, 15) };
    var book3 = new Book { AuthorName = "于蛋", Title = "寡妇", Price = 73, PubTime = new DateTime(2099, 8, 15) };
    var book4 = new Book { AuthorName = "于蛋", Title = "不是所有的虫子都能变成蝴蝶因为有的是他娘的蛆", Price = 95, PubTime = new DateTime(2099, 8, 15) };
    var book5 = new Book { AuthorName = "于蛋", Title = "于玉菊开花", Price = 84, PubTime = new DateTime(2099, 8, 15) };
   
    testDBBook.Books.Add(book1);
    testDBBook.Books.Add(book2);
    testDBBook.Books.Add(book3);
    testDBBook.Books.Add(book4);
    testDBBook.Books.Add(book5);

    await testDBBook.SaveChangesAsync();
}

查看插入结果:

4.2.4 查询数据

查询所有书:

using (TestDbContext testDBBook = new TestDbContext())
{
    Console.WriteLine("***所有书***");
	foreach (var item in testDBBook.Books)
	{
		Console.WriteLine($"ID={item.ID},Title={item .Title },Price={item .Price}");
	}
}

查询价格高于80元的书

using (TestDbContext testDBBook = new TestDbContext())
{
    Console.WriteLine("***价格高于80元人民币的BOOK***");
    IEnumerable<Book> books80 = testDBBook.Books.Where(b => b.Price > 80);

    foreach (var item in books80)
    {
        Console.WriteLine($"ID={item.ID},Title={item.Title},Price={item.Price}");
    }

}

除此之外,在EF Core中还支持其他的LINQ操作,比如Single OrderBy GroupBy等,关于LINQ的相关操作,可以参阅本农之前的学习笔记:第2章 LINQ C#之LINQ .Net CoreLINQ C#Lambda表达式_c# linq core 常用方法-CSDN博客

4.2.5 修改和删除数据

修改:《舌尖上的足疗》作者改为于玉菊

using (TestDbContext testDBBook = new TestDbContext())
{
    var bCHange = testDBBook.Books.Single(b=>b.Title=="舌尖上的足疗");
    bCHange.AuthorName = "于玉菊";
    await testDBBook.SaveChangesAsync();

    Console.WriteLine("***所有书***");
    foreach (var item in testDBBook.Books)
    {
        Console.WriteLine($"ID={item.ID},Title={item.Title},authorName={item.AuthorName}");
    }
}

数据已更改:

删除《磨》这本书

using (TestDbContext testDBBook = new TestDbContext())
{
    var bCHange = testDBBook.Books.Single(b => b.Title == "磨");
    testDBBook.Remove(bCHange);
    await testDBBook.SaveChangesAsync();

    Console.WriteLine("***所有书***");
    foreach (var item in testDBBook.Books)
    {
        Console.WriteLine($"ID={item.ID},Title={item.Title},authorName={item.AuthorName}");
    }
}

数据已删除

对于修改和删除,在EF的底层都是发生了先Select ,然后UpDate或者Delete的过程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值