.net core中根据数据库查询数据

258 阅读1分钟

Nuget引入程序集

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.SqlServer.Design

Microsoft.EntityFrameworkCore.Tools

创建类库

QQ截图20220223104632.png

创建ClassModel,IServer,Server类库

ClassModel中使用Scaffold-DbContext在类中创建sql数据库中的表

Scaffold-DbContext "数据库链接字符串" [-Provider] [-OutputDir ] [-Context ] [-Schemas ] [-Tables ] [-DataAnnotations] [ -Force] [-Project ] [-StartupProject ] [-Environment ] []

例子:Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=GY;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Project GY.Model -Context Entitys -OutputDir "Base" -Force

PARAMETERS -Connection 指定数据库的连接字符串。

-Provider 指定要使用的提供程序。例如,Microsoft.EntityFrameworkCore.SqlServer。

-OutputDir 指定用于输出类的目录。如果省略,则使用顶级项目目录。

-Context 指定生成的DbContext类的名称。

-Schemas 指定要为其生成类的模式。

-Tables 指定要为其生成类的表。

-DataAnnotations [] 使用DataAnnotation属性在可能的情况下配置模型。如果省略,输出代码将仅使用流畅的API。

-Force [] 强制脚手架覆盖现有文件。否则,只有在没有输出文件被覆盖的情况下,代码才会继续。

-Project 指定要使用的项目。如果省略,则使用默认项目。

-StartupProject 指定要使用的启动项目。如果省略,则使用解决方案的启动项目。

-Environment 指定要使用的环境。如果省略,则使用“开发”。

在IServer中创建IBaseContext接口

 public interface IBaseContext
{
    List<Basem> list();
}

在Server中继承IBaseContext接口

public class BaseContext : IBaseContext { protected DbContext db { set; get; }

    public BaseContext(DbContext d)
    {
        db = d;
    }

    public List<Basem> list()
    {
        //using (Model1 db = new Model1())
        //{
        return db.Set<Biao1>().Select(a => new Basem()
        {
            Id=a.Id,
            Nane=a.Nane,
            Age=a.Age
        }).ToList();
        //}

    }
}

创建MVC core在Program中来IOC

    //添加Autofac包  Autofac.Extensions.DependencyInjection包  using Autofac.Extensions.DependencyInjection;
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
//using Autofac;
builder.Host.ConfigureContainer<ContainerBuilder>(a =>
{
    a.RegisterType<BaseContext>().As<IBaseContext>();
    a.RegisterType<ClassModel1>().As<DbContext>();
});

创建控制器Home1Controller

  public class Home1Controller : Controller
{
    public IBaseContext se { get; set; }

    public Home1Controller(IBaseContext a)
    {
        se = a;
    }
    public IActionResult Index()
    {
        //Ibase b = new Basecontext();
        var b = se.list();
        return View(b);
    }
}