.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; }

public string Title { get; set; }

    public DateTime PubTime { get; set; }

    public double Price { get; set; }

}

}

```

创建配置类

对应数据库表

``` 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; }

public DbSet<Person> Persons { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlServer(
            "server=.159.138.73;" +
            "uid=SA;" +
            "pwd=qwer1234.;" +
            "database=demo1_Enviroment;" +
            "TrustServerCertificate=true;"
            );
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // 从当前程序集加载所有的IEntityTypeConfiguration
        modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
    }
}

}

```

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; }

[Required]
    [MaxLength]
    public string Name { get; set; }
}

}

```

配置类添加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; }

public DbSet<Person> Persons { get; set; }

    public DbSet<Cat> Cats { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlServer(
            "server=192.159.138.73;" +
            "uid=SA;" +
            "pwd=qwer1234.;" +
            "database=demo1_Enviroment;" +
            "TrustServerCertificate=true;"

            );
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // 从当前程序集加载所有的IEntityTypeConfiguration
        modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
    }
}

}

```

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()) {

IQueryable<Book> books = context.Books.Where(b => b.Price > 80);
            foreach(var book in books)
            {
                await Console.Out.WriteLineAsync(book.Title+"__"+book.Price);
            }
            await context.SaveChangesAsync();
        }
    }
}

} ```

image.png

查询"西游记"的作者

``` using System.Linq;

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

Book one = context.Books.Single(b => b.Title == "西游记");
            await Console.Out.WriteLineAsync(one.AuthorName);

        }
    }
}

} ```

image.png

价格升序

``` using System.Linq;

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

IOrderedQueryable<Book> books = context.Books.OrderBy(b=>b.Price);
            foreach (Book book in books)
            {
                await Console.Out.WriteLineAsync(book.Title+","+book.Price);
            }

        }
    }
}

} ``` image.png

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

修改部分数据

image.png

``` using System.Linq;

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

var items = context.Books
                .GroupBy(b => b.AuthorName)
                .Select(g => new
                {
                    Name = g.Key,
                    BooksCount = g.Count(),
                    MaxPrice = g.Max(b => b.Price)
                });
            foreach(var item in items)
            {
                await Console.Out.WriteLineAsync($"{item.Name},{item.BooksCount},{item.MaxPrice}");
            }
        }
    }
}

} ```

image.png

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

``` using System.Linq;

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

Book book = context.Books.Single(b=>b.Title=="西游记");
            book.AuthorName = "张三";
            await context.SaveChangesAsync();

        }
    }
}

} ``` 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()) {

Book book = context.Books.Single(b=>b.Id == 6);
            context.Books.Remove(book);
            await context.SaveChangesAsync();

        }
    }
}

} ```

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值