最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

在Asp.Net Core中配置使用EFCore

2020-04-04 20:59 作者:Tuple_元組  | 我要投稿

EFCore 是一個(gè)ORM(對(duì)象關(guān)系映射),它使 .NET 開發(fā)人員可以使用 .NET對(duì)象操作數(shù)據(jù)庫(kù),避免了像ADO.NET訪問數(shù)據(jù)庫(kù)的代碼,開發(fā)者只需要編寫對(duì)象即可。目前,EF Core 支持多種數(shù)據(jù)庫(kù)引擎:Microsoft SQL Sever、SQLite、Npgsql、MySQL

本文以Sqlite數(shù)據(jù)庫(kù)為例,介紹如何在基于 .Net Core 的應(yīng)用程序中(比如:asp.net core)配置使用 EFCore 。主要內(nèi)容包括:

  • 以依賴注入或非依賴注入的方式使用配置EFCore相關(guān)信息

  • 如何通過EFCore 對(duì)數(shù)據(jù)進(jìn)行增刪改查,包括使用Jion進(jìn)行表之間的連接查詢的用法。

一、添加依賴

asp.net core 應(yīng)用程序項(xiàng)目建立好后,添加以下引用。

?Microsoft.EntityFrameworkCore.Sqlite
?Microsoft.EntityFrameworkCore.Tools
?Microsoft.VisualStudio.Web.CodeGeneration.Design

上述三個(gè)引用包中的后兩個(gè),用于數(shù)據(jù)庫(kù)(表)的生成,即Code First 方式時(shí)使用。如不需要通過工具自動(dòng)生成數(shù)據(jù)庫(kù)(表)可不引用之。

二、建立一個(gè)數(shù)據(jù)庫(kù)上下文類

  1. 采用非依賴注入方式。

?public class SqliteDbContext : DbContext

? ? ?{
? ? ? ? ?private string ConnectString = "Data Source=SqliteDatabase.db";
? ? ? ? ?//定義類與表的對(duì)應(yīng)關(guān)系(即:ModeUser類與數(shù)據(jù)庫(kù)中的tb_user表對(duì)應(yīng))
? ? ? ? ?public DbSet<ModelUser> tb_user { set; get; }
? ? ? ? ?//重寫父類中的 ?OnConfiguring 方法。以便初始化相關(guān)配置信息。 ? ? ? ? ? ?
? ? ? ? ?protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
? ? ? ? ?{
? ? ? ? ? ? optionsBuilder.UseSqlite(ConnectString);
? ? ? ? ?}
? ? ? ? ?//重寫父類中的 OnModelCreating 方法。此類中可指定主鍵、指定屬性是否是必須的、指定屬生長(zhǎng)度,或設(shè)置數(shù)據(jù)表之間的關(guān)系等。(根據(jù)需要,可以不重寫該方法)
? ? ? ? ?protected override void OnModelCreating(ModelBuilder modelBuilder)
? ? ? ? ?{
? ? ? ? ? ? ?modelBuilder.Entity<ModelUser>().HasKey(x => x.Id);
? ? ? ? ? ? ?modelBuilder.Entity<ModelUser>().Property("Nick").IsRequired().HasMaxLength(20); ? ? ? ?
? ? ? ? ?}
? ? ?}


? 2.使用依賴注入方式

  • 改寫數(shù)據(jù)庫(kù)上下文類如下:

?public class SqliteDbContext : DbContext
? ? ?{
? ? ? ? ?//使用構(gòu)造函數(shù),相關(guān)的options由框架依賴注入。
? ? ? ? ?public SqliteDbContext(DbContextOptions<SqliteDbContext> options) : base(options)
? ? ? ? ?{
? ? ? ? ?}
? ? ? ? ?//定義類與表的對(duì)應(yīng)關(guān)系(即:ModeUser類與數(shù)據(jù)庫(kù)中的tb_user表對(duì)應(yīng))
? ? ? ? ?public DbSet<ModelUser> tb_user { set; get; } ? ? ? ? ? ?
? ? ? ? ?//重寫父類中的 OnModelCreating 方法。此類中可指定主鍵、指定屬性是否是必須的、指定屬生長(zhǎng)度,或設(shè)置數(shù)據(jù)表之間的關(guān)系等。(根據(jù)需要,可以不重寫該方法)
? ? ? ? ?protected override void OnModelCreating(ModelBuilder modelBuilder)
? ? ? ? ?{
? ? ? ? ? ? ?modelBuilder.Entity<ModelUser>().HasKey(x => x.Id);
? ? ? ? ? ? ?modelBuilder.Entity<ModelUser>().Property("Nick").IsRequired().HasMaxLength(20); ? ? ? ?
? ? ? ? ?}
? ? ?}

  • 在 Startup.cs 文件中的 ConfigureServices 方法中注入系統(tǒng)的 DbContext 對(duì)象。

?services.AddDbContext<SqliteDbContext>(options =>
? ? ?{
? ? ? ? ?options.UseSqlite(Configuration.GetConnectionString("SqliteConnStr"));
? ? ?});

  • 在appsettings.json文中指定字符串連接。

?"ConnectionStrings": {
? ? ?"SqliteConnStr": "Data Source=SqliteDatabase.db"
? ?}

三、建立數(shù)據(jù)操作倉(cāng)庫(kù)類

? public class DataUserRepository
? ? ?{
? ? ? ? ?private readonly SqliteDbContext _DbContext;
?
? ? ? ? ?public DataUserRepository(SqliteDbContext DbContext)
? ? ? ? ?{
? ? ? ? ? ? ?_DbContext = DbContext;
? ? ? ? ?}
? ? ? ? ? /// <summary>
? ? ? ? ?/// 根據(jù)Id查詢用戶信息
? ? ? ? ?/// </summary>
? ? ? ? ?/// <param name="P_Id"></param>
? ? ? ? ?/// <returns></returns>
? ? ? ? ?public async Task<ModelUser> GetOneByIdAsync(string P_Id)
? ? ? ? ?{
? ? ? ? ? ? ?return await _DbContext.tb_user.FindAsync(P_Id);
? ? ? ? ?}
? ? ? ? ?/// <summary>
? ? ? ? ?/// 返回指定條件的所有用戶
? ? ? ? ?/// </summary>
? ? ? ? ?/// <returns></returns>
? ? ? ? ?public async Task<List<ModelUser>> GetAllAsync(Expression<Func<ModelUser, bool>> whereLambda)
? ? ? ? ?{
? ? ? ? ? ? ?return await _DbContext.tb_user.Where(whereLambda).ToListAsync(); ? ? ? ? ? ?
? ? ? ? ?}
? ? ? ? ?/// <summary>
? ? ? ? ?/// 向數(shù)據(jù)庫(kù)表添加一個(gè)新的記錄,如果該記錄已經(jīng)存在,返回-2。
? ? ? ? ?/// </summary>
? ? ? ? ?/// <param name="P_Entity"></param>
? ? ? ? ?/// <returns></returns>
? ? ? ? ?public async Task<int> AddNew(ModelUser P_Entity)
? ? ? ? ?{
? ? ? ? ? ? ?if (P_Entity == null) return -1;
? ? ? ? ? ? ?bool IsExist = _DbContext.tb_user.Count(e => e.Id == P_Entity.Id) > 0;
? ? ? ? ? ? ?if (IsExist)
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?return -2;
? ? ? ? ? ? ?}
? ? ? ? ? ? ?_DbContext.tb_user.Add(P_Entity);
? ? ? ? ? ? ?return await _DbContext.SaveChangesAsync();
? ? ? ? ?}
? ? ? ? ?/// <summary>
? ? ? ? ?/// 根據(jù)Id刪除用戶信息
? ? ? ? ?/// </summary>
? ? ? ? ?/// <param name="P_Id"></param>
? ? ? ? ?/// <returns></returns>
? ? ? ? ?public async Task<int> DelOneByIdAsync(string P_Id)
? ? ? ? ?{
? ? ? ? ? ? ?int actResult = 0;
? ? ? ? ? ? ?if (!string.IsNullOrWhiteSpace(P_Id))
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?ModelUser user = await GetOneByIdAsync(P_Id);
? ? ? ? ? ? ? ? ?if (user != null)
? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ?_DbContext.tb_user.Remove(user);
? ? ? ? ? ? ? ? ? ? ?actResult = await _DbContext.SaveChangesAsync();
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ?}
? ? ? ? ? ? ?return actResult;
? ? ? ? ?}
? ? ? ? ?/// <summary>
? ? ? ? ?/// 刪除所有記錄信息(直接使用SQL語句)
? ? ? ? ?/// </summary>
? ? ? ? ?/// <param name="P_Id"></param>
? ? ? ? ?/// <returns></returns>
? ? ? ? ?public async Task<int> DelAllDatasAsync()
? ? ? ? ?{
? ? ? ? ? ? ?int actResult = await _DbContext.Database.ExecuteSqlRawAsync($"DELETE FROM TB_USER WHERE Role<>'Admin'");
? ? ? ? ? ? ?return actResult;
? ? ? ? ?}
? ? ? ? ?/// <summary>
? ? ? ? ?/// 更改指定用戶的密碼
? ? ? ? ?/// </summary>
? ? ? ? ?/// <param name="P_Id"></param>
? ? ? ? ?/// <param name="p_newPwd"></param>
? ? ? ? ?/// <returns></returns>
? ? ? ? ?public async Task<int> ChangePwd(string P_Id, string p_newPwd)
? ? ? ? ?{
? ? ? ? ? ? ?int actResult = 0;
? ? ? ? ? ? ?if (!string.IsNullOrWhiteSpace(P_Id))
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?ModelUser user = await GetOneByIdAsync(P_Id);
? ? ? ? ? ? ? ? ?if (user != null)
? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ?user.Pwd = p_newPwd;
? ? ? ? ? ? ? ? ? ? ?_DbContext.Update(user);
? ? ? ? ? ? ? ? ? ? ?actResult = await _DbContext.SaveChangesAsync();
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ?}
? ? ? ? ? ? ?return actResult;
? ? ? ? ?}
? ? ?}

上述數(shù)據(jù)操作類建好后,可以在Controller中使用。

其他內(nèi)容

  1. 兩個(gè)數(shù)據(jù)庫(kù)連接查詢(不需要建數(shù)據(jù)表時(shí)指定外鍵)

? var scoreList = await _DbContext.tb_score.Join(_DbContext.tb_user, pet => pet.UserId, per => per.Id, (pet, per) => new
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?ProgramId=pet.ProgramId,
? ? ? ? ? ? ? ? ?Score=pet.Score,
? ? ? ? ? ? ? ? ?userRole = per.Role,
? ? ? ? ? ? ? ? ?userUnit = per.Unit
? ? ? ? ? ? ?}).Where(e => e.ProgramId.Equals(P_ProgramId)).ToListAsync();
?此代碼中pet代表 tb_score 表對(duì)象,per 代表 tb_user 表對(duì)象,兩者通過 pet.UserId==per.Id 條件進(jìn)行連接查詢。

當(dāng)然,如果在建表時(shí)已經(jīng)指定了外鍵關(guān)系,則可通過 Include() 進(jìn)行查詢。

?_DbContext.tb_score.Include(o=>o.tb_user).SingleOrDefault(e => e.Score=100);

2.?關(guān)于數(shù)據(jù)遷移。 通過控制臺(tái)創(chuàng)建數(shù)據(jù)庫(kù),即使用本文開頭引用的后兩個(gè)程序包。

?PM> get-help entityframeworkcore //可以先查看一下支持哪些命令
? Cmdlet ? ? ? ? ? ? ? ? ? ? ?Description
? Add-Migration ? ? ? ? ? ? ? Adds a new migration.
? Drop-Database ? ? ? ? ? ? ? Drops the database.
? Get-DbContext ? ? ? ? ? ? ? Gets information about a DbContext type.
? Remove-Migration ? ? ? ? ? ?Removes the last migration.
? Scaffold-DbContext ? ? ? ? ?Scaffolds a DbContext and entity types for a database.
? Script-DbContext ? ? ? ? ? ?Generates a SQL script from the current DbContext.
? Script-Migration ? ? ? ? ? ?Generates a SQL script from migrations.
? Update-Database ? ? ? ? ? ? Updates the database to a specified migration.
?
? PM> Add-Migration InitDatabase //生成數(shù)據(jù)遷移文件,其中‘InitDatabase’是為本次遷移的命名
? ...
? PM> Update-Database ? ? ? ? ? //運(yùn)行遷移文件,生成相應(yīng)的數(shù)據(jù)庫(kù)和表。
? ...


在Asp.Net Core中配置使用EFCore的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國(guó)家法律
盐山县| 天门市| 自贡市| 合肥市| 乐陵市| 嘉荫县| 石泉县| 越西县| 淳化县| 宁津县| 元江| 扎囊县| 高淳县| 怀化市| 彰化市| 龙山县| 卢龙县| 全南县| 厦门市| 通榆县| 夹江县| 甘谷县| 禹城市| 攀枝花市| 海安县| 乌拉特前旗| 尼木县| 太仆寺旗| 扎鲁特旗| 云霄县| 鸡东县| 台湾省| 延庆县| 蒙城县| 印江| 柳江县| 深圳市| 九龙城区| 广宗县| 文安县| 东光县|