使用EFCore进行增删改查
一、添加数据
//dbcontext 逻辑上的数据库,并不是真实的
Book book1 = new Book { AuthorName = "lty1", Tittle = "深入浅出EFCore", Price = 1.80, PublicTime = new DateTime(2021, 12, 16) };
Book book2 = new Book { AuthorName = "lty2", Tittle = "深入浅出数据结构", Price = 1.80, PublicTime = new DateTime(2021, 12, 16) };
Book book3 = new Book { AuthorName = "lty3", Tittle = "深入浅出算法分析", Price = 1.80, PublicTime = new DateTime(2021, 12, 16) };
Book book4 = new Book { AuthorName = "lty4", Tittle = "深入浅出MySql", Price = 1.80, PublicTime = new DateTime(2021, 12, 16) };
Book book5 = new Book { AuthorName = "lty5", Tittle = "深入浅出计算机网络", Price = 1.80, PublicTime = new DateTime(2021, 12, 16) };
//把Book加入到逻辑上的Book表中
dbcontext.Book.Add(book1);
dbcontext.Book.Add(book2);
dbcontext.Book.Add(book3);
dbcontext.Book.Add(book4);
dbcontext.Book.Add(book5);
//这会把逻辑上的数据库表,更新到真实的数据库中
await dbcontext.SaveChangesAsync();
#endregion
二、查看数据
1.DbSet
DbSet返回的IQueryable类型,可以说是EFCore的linq,IQueryable继承了IEnumerable所以可以使用linq语句,EFCore会转换为Sql语句
2.查询语句,其他条件查询,这里不做解释,可以自行查询
三、修改
修改步骤:
1.对要修改的数据先查出来
2.进行修改
3.再保存
var data_Alter = dbcontext.Book.Single(b => b.Tittle == "深入浅出算法分析");
data_Alter.AuthorName = "深入浅出算法分析的AuthorName";
dbcontext.SaveChanges();
四、删除
1.现有数据
删除代码
var data_Delete = dbcontext.Dogs.Single(b => b.Name == "HaSai");
dbcontext.Remove(data_Delete);
dbcontext.SaveChanges();
删除后数据库的数据消失
五、EFCore不足
暂时不支持批量的删除修改。
SqlServer数据库可以使用这个来查询近期的sql执行