【EF Core】增删改查Demo


插入

using (TestDbContext ctx = new TestDbContext())
{
    var b1 = new Book
    {
        AuthorName = "杨中科",
        Title = "零基础趣学C语言",
        Price = 59.8,
        PubTime = new DateTime(2019, 3, 1)
    };
    var b2 = new Book
    {
        AuthorName = "Robert Sedgewick",
        Title = "算法(第4版)",
        Price = 99,
        PubTime = new DateTime(2012, 10, 1)
    };
    var b3 = new Book
    {
        AuthorName = "吴军",
        Title = "数学之美",
        Price = 69,
        PubTime = new DateTime(2020, 5, 1)
    };
    var b4 = new Book
    {
        AuthorName = "杨中科",
        Title = "程序员的SQL金典",
        Price = 52,
        PubTime = new DateTime(2008, 9, 1)
    };
    var b5 = new Book
    {
        AuthorName = "吴军",
        Title = "文明之光",
        Price = 246,
        PubTime = new DateTime(2017, 3, 1)
    };
    ctx.Books.Add(b1);
    ctx.Books.Add(b2);
    ctx.Books.Add(b3);
    ctx.Books.Add(b4);
    ctx.Books.Add(b5);
    await ctx.SaveChangesAsync();
}

查询

using (TestDbContext ctx = new TestDbContext())
{
    //查询全部
    foreach (var b in ctx.Books)
    {
        Console.WriteLine($"Id={b.Id},Title={b.Title},Price={b.Price}");
    }
    Console.WriteLine("----------------");

    //按条件查询,并且排序
    foreach (var b in ctx.Books.Where(b => b.Price > 80).OrderByDescending(b => b.Id))
    {
        Console.WriteLine($"Id={b.Id},Title={b.Title},Price={b.Price}");
    }
    Console.WriteLine("----------------");

    //Single
    var book = ctx.Books.FirstOrDefault(b => b.Id == 1);
    Console.WriteLine($"Id={book.Id},Title={book.Title},Price={book.Price}");
    Console.WriteLine("----------------");

    //分组查询
    var groups = ctx.Books.GroupBy(b => b.AuthorName).Select(g => new { AuthorName = g.Key, BooksCount = g.Count(), MaxPrice = g.Max(b => b.Price) });
    foreach (var g in groups)
    {
        Console.WriteLine($"作者:{g.AuthorName},图书数量:{g.BooksCount},最高价格:{g.MaxPrice}");
    }
}

修改

using (TestDbContext ctx = new TestDbContext())
{
    var book = ctx.Books.FirstOrDefault(b => b.Id == 1);
    book.Price = 100;
    ctx.SaveChanges();
}

删除

using (TestDbContext ctx = new TestDbContext())
{
    var book = ctx.Books.FirstOrDefault(b => b.Id == 4);
    ctx.Remove(book);
    //ctx.Books.Remove(book);//这种方式也可以
    ctx.SaveChanges();
}