aspnetcore2.0中entityframeworkcore及autofac的使用(附demo)((代码片段)

mrliu90 mrliu90     2023-01-29     335

关键词:

一,通过Entityframeworkcore中DbFirst模式创建模型

这里只说一下Entityframeworkcore中DbFirst模式创建模型,想了解CodeFirst的可以自行度娘,还是在原有项目中创建一个Model类库,然后通过通过vs中NuGet的程序包管理控制台执行

 技术分享图片

安装EntityFrameworkCore类工具包,:

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.SqlServer.Design

Microsoft.EntityFrameworkCore.Tools

技术分享图片

 

注意安装以下类库版本需与AspNetCore.Model自建类库的Core版本相适应。

通过执行以下命令生成实体类与上下文

 Scaffold-dbcontext "Server=.;database=test1;Integrated Security=false;user id=****;password=*****" Microsoft.EntityFrameworkCore.SqlServer -outputdir Models

技术分享图片

 技术分享图片

生成成功后要修改一下test1Context.cs中的代码

 //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //
        //    if (!optionsBuilder.IsConfigured)
        //    
        //        optionsBuilder.UseSqlServer(@"Server=zhang;database=test1;Integrated Security=false;user id=sa;password=123456");
        //    
        //

        //自定义定义构造器
        public test1Context(DbContextOptions options):base(options)
        

        

注意:每次更新数据库都要修改test1Context.cs中的代码

新建BookService.cs

技术分享图片
namespace AspNetCore.Service

    public class BookService
    
        private test1Context _context = null;

        public BookService(test1Context context)
        
            this._context = context;
        


        public Book Get(long id)
        
            return _context.Book.Find(id);
        
    
View Code

下一步我们就要通过Controller把数据呈现出来,在这里我们要把数据库连接放到appsettings.json配置文件里

技术分享图片

    "ConnectionStrings": 
        "connstr": "Data Source=.;Initial Catalog=test1;User ID=*****; Password=**********"
    ,
    "Logging": 
        "IncludeScopes": false,
        "LogLevel": 
            "Default": "Warning"
        
    
View Code

修改一下项目启动文件Startup.cs:

技术分享图片
 public void ConfigureServices(IServiceCollection services)
        
            services.AddMvc();
            //配置上下文
            services.AddDbContext<test1Context>(options => options.UseSqlServer(Configuration.GetConnectionString("connstr")));
            //默认类库声明周期
            services.AddScoped(typeof(BookService));
        
View Code

新建BookController中的代码:

技术分享图片
public class BookController : Controller
    
        //依赖注入
        private readonly BookService _service = null;
        public BookController(BookService service)
        
            this._service = service;
        

        public IActionResult Index()
        
            return Content($"第一本书的书名是[_service.Get(1).Name]") ;
        
    
View Code

结果:

技术分享图片

 

 ^v^是不是很开森

 

同一站点中的 asp net core 2.0 JWT 和 Openid Connect 身份验证

】同一站点中的aspnetcore2.0JWT和OpenidConnect身份验证【英文标题】:aspnetcore2.0JWTandOpenIDConnectAuthenticationinsamesite【发布时间】:2018-07-0316:43:48【问题描述】:我们有一个aspnetcore2.0网站。该网站的大部分内容是WebAPI,有2个UI组件:swag... 查看详情

带有 EF6 和 dotConnect for oracle 的 aspnetcore 2.0

】带有EF6和dotConnectfororacle的aspnetcore2.0【英文标题】:aspnetcore2.0withEF6anddotConnectfororacle【发布时间】:2018-01-2420:59:19【问题描述】:我正在尝试使用dotConnectforOracle(v9.4)来使用Oracle。由于aspnetcore2.0完全支持引用较旧的.net框架,我... 查看详情

如何告诉 Entity Framework 我的 ID 列是自动递增的(AspNet Core 2.0 + PostgreSQL)?

】如何告诉EntityFramework我的ID列是自动递增的(AspNetCore2.0+PostgreSQL)?【英文标题】:HowtotellEntityFrameworkthatmyIDcolumnisauto-incremented(AspNetCore2.0+PostgreSQL)?【发布时间】:2018-10-1613:59:16【问题描述】:代码很简单。Tag.cs实体:publicparti... 查看详情

在 AspNetCore 中使用 Rotativa 将 Html 转换为 Pdf

...布时间】:2018-12-1912:39:31【问题描述】:我使用rotativa在aspnetcore2.0中生成pdf视图。生成效果很好,我的疑问是关于响应。如果我使用这个代码块工作,当我点击按钮时它会自动下载:@using(Html.BeginForm(null,n 查看详情

使用 AspNet Core 2.0 进行 Google JWT 身份验证

】使用AspNetCore2.0进行GoogleJWT身份验证【英文标题】:GoogleJWTAuthenticationwithAspNetCore2.0【发布时间】:2018-07-2112:38:18【问题描述】:我正在尝试将google身份验证集成到我的ASP.NETCore2.0Webapi中,但我不知道如何让它工作。我的Startup.csC... 查看详情

如何在 T4 中实例化 EF6 上下文?

...架提供程序类型“System.Data.Entity.SqlServer.SqlProviderServices,EntityFram 查看详情

获取实体框架 6 在其下面的 SELECT 语句中使用 NOLOCK

...框架6在其下面的SELECT语句中使用NOLOCK【英文标题】:GetEntityFramework6useNOLOCKinitsunderneathSELECTstatements【发布时间】:2014-09-0107:44:29【问题描述】:我在MVC5项目中使用实体框架6。如您所知,如果我们在其中使用WITH(NOLOCK),SQLServer中... 查看详情

Scaffold-DbContext:找不到命令

...ext"Server=(db);Database=xxxx;Trusted_connection=true;"Microsoft.EntityFram 查看详情

迁移到实体框架自定义 ORM

】迁移到实体框架自定义ORM【英文标题】:MigratingtoEntityFrameworkcustomORM【发布时间】:2011-11-0803:02:29【问题描述】:我们目前有一个完全用ASP.NET和MVC手工编写的解决方案。目前DAL中有很多丑陋的hack和变通方法,我没有对这些hack... 查看详情

如何在 c# 实体框架核心中使用 FromSqlRaw() 将 OUTPUT 参数发送到 MySql 存储过程

...题】:HowsendOUTPUTparametertoMySqlstoredprocedureusingFromSqlRaw()inc#entityframeworkcore【发布时间】:2021-10-0722:27:51【问题描述】:在VisualStudioCodeC#项目中,我使用的是Microsoft.EntityFrame 查看详情

无法使用连接字符串名称运行支架 dbcontext

...控制台中使用的命令是:Scaffold-DbContextName="pwa_db"Microsoft.EntityFram 查看详情

如何使用efcore按周对数据分组?(代码片段)

咨询区Aza:在EntityFramework6中,我可以用SqlFunctions.DatePart()函数来实现,参考如下代码:var byWeek = data.GroupBy(x => SqlFunctions.DatePart("week", x.Date));现在的问题是,EntityFram 查看详情

sql 到对象映射实体框架的疑难解答

...框架的疑难解答【英文标题】:troubleshootingsqltoobjectmappingentityframework【发布时间】:2020-10-3116:23:28【问题描述】:我的问题是:如何从SQLServer返回的记录中调试映射过程,因为它被映射到类对象,以便我可以准确地知道哪个类属... 查看详情

如何在 ASP.NET MVC 5、Entity Framework 6 中使用流利的 API 映射表?

】如何在ASP.NETMVC5、EntityFramework6中使用流利的API映射表?【英文标题】:HowcanImaptablesusingfluentAPIinASP.NETMVC5,EntityFramework6?【发布时间】:2013-10-2717:22:32【问题描述】:我正在尝试使用带有内置用户身份验证的ASP.NETMVC5在EntityFramework... 查看详情

efcore新特性——ownedentitytypes(代码片段)

...本那个人的地址。https://www.cnblogs.com/xishuai/p/ddd_valueobject_entityframe 查看详情

更新方法 - 值不能为空。 (参数“实体”)

...mentNullException:值不能为空。(参数“实体”)在Microsoft.EntityFram 查看详情

与 Entity Framework Core 2.0 的一对零关系

】与EntityFrameworkCore2.0的一对零关系【英文标题】:One-to-ZerorelationshipwithEntityFrameworkCore2.0【发布时间】:2018-03-0812:54:16【问题描述】:我正在使用C#和.NETFramework4.7将EntityFramework6.1.3CodeFirst库迁移到EntityFrameworkCore。我一直在用Google... 查看详情

如何在 Entity Framework 4.4 中实现 DBSet.AddOrUpdate?

】如何在EntityFramework4.4中实现DBSet.AddOrUpdate?【英文标题】:HowcanIimplementDBSet.AddOrUpdateinEntityFramework4.4?【发布时间】:2013-08-0110:41:11【问题描述】:为了回应Slauma对我的问题aboutrunningapplicationsthatuseEFonWindowsXP的回答,我正在将我... 查看详情