asp.net core 2.1 dotnet(三)EF.core 的增,删,改,查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiajing13579/article/details/82834480

1.调用方式:

   增加引用: 

        using Microsoft.EntityFrameworkCore;

        using Newtonsoft;

增加加载的类构造函数:

    APPDbContext _context;

    public ValuesController(APPDbContext context){

    this._context = context;

   }

2.在appsettings.json中增加 配置 如下:

{

"ConnectionStrings": {

"SqlServerConnection": "Server=.;Database=dbCore;User ID=sa;Password=password;"

},

"Logging": {

"LogLevel": {

"Default": "Warning"

}

},

"AllowedHosts": "*"

}

3.增加 APPDbContext类

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using Microsoft.EntityFrameworkCore;

using CoreAPI.Mdoel;

namespace CoreAPI

{

public class APPDbContext:DbContext

{

public APPDbContext(DbContextOptions<APPDbContext> options):base(options)

{

}

public DbSet<User> User { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

base.OnModelCreating(modelBuilder);

}

}

}

4.增加的例子:

这个和调用别EF 的方式一样。

CoreAPI.Mdoel.User user = new CoreAPI.Mdoel.User();

user.UserName = "tesd2";

user.Password = "password";

_context.Add(user);

_context.SaveChanges();

5. 修改的例子:

var v1 = _context.User.Where(c=>c.Id==2); //得到数据库中的一行。

User user = v1.Take(1).Single();

user.password = "test";

_context.SaveChanges();

6.删除的例子

var v1 = _context.User.Where(c=>c.Id==2);

CoreAPI.Mdoel.User user1= v1.Take(1).Single();

_context.User.Remove(user1);

_context.SaveChanges();

7.查找的例子

var v2 = from t in _context.User select t;

foreach(var item in v2){

Console.Write(item.Id.ToString()+":"+ item.UserName);

}

8.事务,这个还没有试,稍后再加上

猜你喜欢

转载自blog.csdn.net/xiajing13579/article/details/82834480