当前位置:   article > 正文

.net EFCore基本操作

.net efcore

theme: smartblue

环境搭建

下载包

Microsoft.EntityFrameworkCore.SqlServer image.png

Microsoft.EntityFrameworkCore.Tools

image.png

创建实体类Book

``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace EFCore { public class Book { public int Id { get; set; }

  1. public string Title { get; set; }
  2. public DateTime PubTime { get; set; }
  3. public double Price { get; set; }
  4. }

}

```

创建配置类

对应数据库表

``` using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace EFCore { public class BookConfig : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { builder.ToTable("T_Books"); builder.Property(b=> b.Title) .HasMaxLength(50).IsRequired(); builder.Property(b=> b.AuthorName) .HasMaxLength(20).IsRequired(); } } }

```

对应数据库配置

``` using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace EFCore { public class MyDBContext:DbContext { public DbSet Books { get; set; }

  1. public DbSet<Person> Persons { get; set; }
  2. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  3. {
  4. base.OnConfiguring(optionsBuilder);
  5. optionsBuilder.UseSqlServer(
  6. "server=.159.138.73;" +
  7. "uid=SA;" +
  8. "pwd=qwer1234.;" +
  9. "database=demo1_Enviroment;" +
  10. "TrustServerCertificate=true;"
  11. );
  12. }
  13. protected override void OnModelCreating(ModelBuilder modelBuilder)
  14. {
  15. base.OnModelCreating(modelBuilder);
  16. // 从当前程序集加载所有的IEntityTypeConfiguration
  17. modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
  18. }
  19. }

}

```

Migration

初始化

显示控制台

image.png

控制台输入Add-Migration Init,初始化创表语句

image.png

控制台输入Update-Database,同步数据

image.png

image.png

添加修改

对 person 类添加了一个属性BirthPlace

控制台输入 Add-Migration AddBirth

image.png

Update-Database同步数据

image.png

Data Annotation

新增实体类cat

``` using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace EFCore { [Table("T_Cats")] public class Cat { public long Id { get; set; }

  1. [Required]
  2. [MaxLength]
  3. public string Name { get; set; }
  4. }

}

```

配置类添加cat

image.png

``` using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace EFCore { public class MyDBContext:DbContext { public DbSet Books { get; set; }

  1. public DbSet<Person> Persons { get; set; }
  2. public DbSet<Cat> Cats { get; set; }
  3. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  4. {
  5. base.OnConfiguring(optionsBuilder);
  6. optionsBuilder.UseSqlServer(
  7. "server=192.159.138.73;" +
  8. "uid=SA;" +
  9. "pwd=qwer1234.;" +
  10. "database=demo1_Enviroment;" +
  11. "TrustServerCertificate=true;"
  12. );
  13. }
  14. protected override void OnModelCreating(ModelBuilder modelBuilder)
  15. {
  16. base.OnModelCreating(modelBuilder);
  17. // 从当前程序集加载所有的IEntityTypeConfiguration
  18. modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
  19. }
  20. }

}

```

Add-Migration addCatUpdate-Database

image.png

增删改查

添加一条图书信息

namespace EFCore { public class Program { static async Task Main(string[] args) { // context 相当于逻辑上的数据库 using (MyDBContext context = new MyDBContext()) { Book book = new Book(); book.Title = "西游记"; book.AuthorName = "吴承恩"; context.Books.Add(book); await context.SaveChangesAsync(); } } } }

image.png

已知有如下数据:

image.png

查询价格大于 80 的书籍信息

``` using System.Linq;

namespace EFCore { public class Program { static async Task Main(string[] args) {
// context 相当于逻辑上的数据库 using (MyDBContext context = new MyDBContext()) {

  1. IQueryable<Book> books = context.Books.Where(b => b.Price > 80);
  2. foreach(var book in books)
  3. {
  4. await Console.Out.WriteLineAsync(book.Title+"__"+book.Price);
  5. }
  6. await context.SaveChangesAsync();
  7. }
  8. }
  9. }

} ```

image.png

查询"西游记"的作者

``` using System.Linq;

namespace EFCore { public class Program { static async Task Main(string[] args) {
// context 相当于逻辑上的数据库 using (MyDBContext context = new MyDBContext()) {

  1. Book one = context.Books.Single(b => b.Title == "西游记");
  2. await Console.Out.WriteLineAsync(one.AuthorName);
  3. }
  4. }
  5. }

} ```

image.png

价格升序

``` using System.Linq;

namespace EFCore { public class Program { static async Task Main(string[] args) {
// context 相当于逻辑上的数据库 using (MyDBContext context = new MyDBContext()) {

  1. IOrderedQueryable<Book> books = context.Books.OrderBy(b=>b.Price);
  2. foreach (Book book in books)
  3. {
  4. await Console.Out.WriteLineAsync(book.Title+","+book.Price);
  5. }
  6. }
  7. }
  8. }

} ``` image.png

按照作者名称分组,查询出版书籍数量以及售卖书籍最贵的价格

修改部分数据

image.png

``` using System.Linq;

namespace EFCore { public class Program { static async Task Main(string[] args) {
// context 相当于逻辑上的数据库 using (MyDBContext context = new MyDBContext()) {

  1. var items = context.Books
  2. .GroupBy(b => b.AuthorName)
  3. .Select(g => new
  4. {
  5. Name = g.Key,
  6. BooksCount = g.Count(),
  7. MaxPrice = g.Max(b => b.Price)
  8. });
  9. foreach(var item in items)
  10. {
  11. await Console.Out.WriteLineAsync($"{item.Name},{item.BooksCount},{item.MaxPrice}");
  12. }
  13. }
  14. }
  15. }

} ```

image.png

将西游记的作者修改为张三

``` using System.Linq;

namespace EFCore { public class Program { static async Task Main(string[] args) {
// context 相当于逻辑上的数据库 using (MyDBContext context = new MyDBContext()) {

  1. Book book = context.Books.Single(b=>b.Title=="西游记");
  2. book.AuthorName = "张三";
  3. await context.SaveChangesAsync();
  4. }
  5. }
  6. }

} ``` image.png

为所有价格大于10的书籍涨10块钱

涨价前

image.png

涨价后

image.png

``` using System.Linq;

namespace EFCore { public class Program { static async Task Main(string[] args) { // context 相当于逻辑上的数据库 using (MyDBContext context = new MyDBContext()) { IQueryable books = context.Books.Where(b => b.Price > 10); foreach(var b in books) { b.Price = b.Price + 10; } await context.SaveChangesAsync(); } } } }

```

删除编号为6的书籍

``` using System.Linq;

namespace EFCore { public class Program { static async Task Main(string[] args) {
// context 相当于逻辑上的数据库 using (MyDBContext context = new MyDBContext()) {

  1. Book book = context.Books.Single(b=>b.Id == 6);
  2. context.Books.Remove(book);
  3. await context.SaveChangesAsync();
  4. }
  5. }
  6. }

} ```

image.png

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/253489
推荐阅读
相关标签
  

闽ICP备14008679号