最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

利用EF6簡單實現(xiàn)多租戶的應(yīng)用

 更新時間:2019年09月10日 09:38:22   作者:阿新  
這篇文章主要給大家介紹了關(guān)于如何利用EF6簡單實現(xiàn)多租戶應(yīng)用的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用EF6具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

什么是多租戶

網(wǎng)上有好多解釋,有些上升到了架構(gòu)設(shè)計,讓你覺得似乎非常高深莫測,特別是目前流行的ABP架構(gòu)中就有提到多租戶(IMustHaveTenant),其實說的簡單一點就是再每一張數(shù)據(jù)庫的表中添加一個TenantId的字段,用于區(qū)分屬于不同的租戶(或是說不同的用戶組)的數(shù)據(jù)。關(guān)鍵是現(xiàn)實的方式必須對開發(fā)人員來說是透明的,不需要關(guān)注這個字段的信息,由后臺或是封裝在基類中實現(xiàn)數(shù)據(jù)的篩選和更新。

基本原理

從新用戶注冊時就必須指定用戶的TenantId,我的例子是用CompanyId,公司信息做為TenantId,哪些用戶屬于不同的公司,每個用戶將來只能修改和查詢屬于本公司的數(shù)據(jù)。

接下來就是用戶登錄的時候獲取用戶信息的時候把TenantId保存起來,asp.net mvc(不是 core) 是通過 Identity 2.0實現(xiàn)的認證和授權(quán),這里需要重寫部分代碼來實現(xiàn)。

最后用戶對數(shù)據(jù)查詢/修改/新增時把用戶信息中TenantId,這里就需要設(shè)定一個Filter(過濾器)和每次SaveChange的插入TenantId

如何實現(xiàn)

第一步,擴展 Asp.net Identity user 屬性,必須新增一個TenantId字段,根據(jù)Asp.net Mvc 自帶的項目模板修改IdentityModels.cs 這個文件

// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
 public class ApplicationUser : IdentityUser
 {
 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
 {
  // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
  var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
  // Add custom user claims here
  userIdentity.AddClaim(new Claim("http://schemas.microsoft.com/identity/claims/tenantid", this.TenantId.ToString()));
  userIdentity.AddClaim(new Claim("CompanyName", this.CompanyName));
  userIdentity.AddClaim(new Claim("EnabledChat", this.EnabledChat.ToString()));
  userIdentity.AddClaim(new Claim("FullName", this.FullName));
  userIdentity.AddClaim(new Claim("AvatarsX50", this.AvatarsX50));
  userIdentity.AddClaim(new Claim("AvatarsX120", this.AvatarsX120));
  return userIdentity;
 }
 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
 {
  // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
  var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
  // Add custom user claims here
  return userIdentity;
 }

 [Display(Name = "全名")]
 public string FullName { get; set; }
 [Display(Name = "性別")]
 public int Gender { get; set; }
 public int AccountType { get; set; }
 [Display(Name = "所屬公司")]
 public string CompanyCode { get; set; }
 [Display(Name = "公司名稱")]
 public string CompanyName { get; set; }
 [Display(Name = "是否在線")]
 public bool IsOnline { get; set; }
 [Display(Name = "是否開啟聊天功能")]
 public bool EnabledChat { get; set; }
 [Display(Name = "小頭像")]
 public string AvatarsX50 { get; set; }
 [Display(Name = "大頭像")]
 public string AvatarsX120 { get; set; }
 [Display(Name = "租戶ID")]
 public int TenantId { get; set; }
 }



 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
 {
 public ApplicationDbContext()
  : base("DefaultConnection", throwIfV1Schema: false) => Database.SetInitializer<ApplicationDbContext>(null);

 public static ApplicationDbContext Create() => new ApplicationDbContext();


 }

第二步 修改注冊用戶的代碼,注冊新用戶的時候需要選擇所屬的公司信息

[HttpPost]
 [AllowAnonymous]
 [ValidateAntiForgeryToken]
 public async Task<ActionResult> Register(AccountRegistrationModel viewModel)
 {
  var data = this._companyService.Queryable().Select(x => new ListItem() { Value = x.Id.ToString(), Text = x.Name });
  this.ViewBag.companylist = data;

  // Ensure we have a valid viewModel to work with
  if (!this.ModelState.IsValid)
  {
  return this.View(viewModel);
  }

  // Try to create a user with the given identity
  try
  {
  // Prepare the identity with the provided information
  var user = new ApplicationUser
  {
   UserName = viewModel.Username,
   FullName = viewModel.Lastname + "." + viewModel.Firstname,
   CompanyCode = viewModel.CompanyCode,
   CompanyName = viewModel.CompanyName,
   TenantId=viewModel.TenantId,
   Email = viewModel.Email,
   AccountType = 0
   
  };
  var result = await this.UserManager.CreateAsync(user, viewModel.Password);

  // If the user could not be created
  if (!result.Succeeded)
  {
   // Add all errors to the page so they can be used to display what went wrong
   this.AddErrors(result);

   return this.View(viewModel);
  }

  // If the user was able to be created we can sign it in immediately
  // Note: Consider using the email verification proces
  await this.SignInAsync(user, true);

  return this.RedirectToLocal();
  }
  catch (DbEntityValidationException ex)
  {
  // Add all errors to the page so they can be used to display what went wrong
  this.AddErrors(ex);

  return this.View(viewModel);
  }
 }

AccountController.cs

第三步 讀取登錄用戶的TenantId 在用戶查詢和新增修改時把TenantId插入到表中,這里需要引用

Z.EntityFramework.Plus,這個是免費開源的一個類庫,功能強大

public StoreContext()
  : base("Name=DefaultConnection") {
  //獲取登錄用戶信息,tenantid
  var claimsidentity = (ClaimsIdentity)HttpContext.Current.User.Identity;
  var tenantclaim = claimsidentity?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid");
  var tenantid = Convert.ToInt32(tenantclaim?.Value);
  //設(shè)置當(dāng)對Work對象進行查詢時默認添加過濾條件
  QueryFilterManager.Filter<Work>(q => q.Where(x => x.TenantId == tenantid));
  //設(shè)置當(dāng)對Order對象進行查詢時默認添加過濾條件
  QueryFilterManager.Filter<Order>(q => q.Where(x => x.TenantId == tenantid));
 }

 public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
 {
  var currentDateTime = DateTime.Now;
  var claimsidentity = (ClaimsIdentity)HttpContext.Current.User.Identity;
  var tenantclaim = claimsidentity?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid");
  var tenantid = Convert.ToInt32(tenantclaim?.Value);
  foreach (var auditableEntity in this.ChangeTracker.Entries<Entity>())
  {
  if (auditableEntity.State == EntityState.Added || auditableEntity.State == EntityState.Modified)
  {
   //auditableEntity.Entity.LastModifiedDate = currentDateTime;
   switch (auditableEntity.State)
   {
   case EntityState.Added:
    auditableEntity.Property("LastModifiedDate").IsModified = false;
    auditableEntity.Property("LastModifiedBy").IsModified = false;
    auditableEntity.Entity.CreatedDate = currentDateTime;
    auditableEntity.Entity.CreatedBy = claimsidentity.Name;
    auditableEntity.Entity.TenantId = tenantid;
    break;
   case EntityState.Modified:
    auditableEntity.Property("CreatedDate").IsModified = false;
    auditableEntity.Property("CreatedBy").IsModified = false;
    auditableEntity.Entity.LastModifiedDate = currentDateTime;
    auditableEntity.Entity.LastModifiedBy = claimsidentity.Name;
    auditableEntity.Entity.TenantId = tenantid;
    //if (auditableEntity.Property(p => p.Created).IsModified || auditableEntity.Property(p => p.CreatedBy).IsModified)
    //{
    // throw new DbEntityValidationException(string.Format("Attempt to change created audit trails on a modified {0}", auditableEntity.Entity.GetType().FullName));
    //}
    break;
   }
  }
  }
  return base.SaveChangesAsync(cancellationToken);
 }

 public override int SaveChanges()
 {
  var currentDateTime = DateTime.Now;
  var claimsidentity =(ClaimsIdentity)HttpContext.Current.User.Identity;
  var tenantclaim = claimsidentity?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid");
  var tenantid = Convert.ToInt32(tenantclaim?.Value);
  foreach (var auditableEntity in this.ChangeTracker.Entries<Entity>())
  {
  if (auditableEntity.State == EntityState.Added || auditableEntity.State == EntityState.Modified)
  {
   auditableEntity.Entity.LastModifiedDate = currentDateTime;
   switch (auditableEntity.State)
   {
   case EntityState.Added:
    auditableEntity.Property("LastModifiedDate").IsModified = false;
    auditableEntity.Property("LastModifiedBy").IsModified = false;
    auditableEntity.Entity.CreatedDate = currentDateTime;
    auditableEntity.Entity.CreatedBy = claimsidentity.Name;
    auditableEntity.Entity.TenantId = tenantid;
    break;
   case EntityState.Modified:
    auditableEntity.Property("CreatedDate").IsModified = false;
    auditableEntity.Property("CreatedBy").IsModified = false;
    auditableEntity.Entity.LastModifiedDate = currentDateTime;
    auditableEntity.Entity.LastModifiedBy = claimsidentity.Name;
    auditableEntity.Entity.TenantId = tenantid;
    break;
   }
  }
  }
  return base.SaveChanges();
 }

DbContext.cs

經(jīng)過以上3步就實現(xiàn)一個簡單的多租戶查詢數(shù)據(jù)的功能。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。

您可能感興趣的文章:

相關(guān)文章

  • ASP.NET?使用?Dispose?釋放資源的四種方法詳細介紹

    ASP.NET?使用?Dispose?釋放資源的四種方法詳細介紹

    本篇文章主要介紹了ASP.NET?使用?Dispose?釋放資源的四種方法,有興趣的同學(xué)可以來看看,喜歡的話記得收藏一下哦,方便下次瀏覽觀看
    2021-11-11
  • .NET中OpenFileDialog使用線程報錯的解決方法

    .NET中OpenFileDialog使用線程報錯的解決方法

    這篇文章主要為大家詳細介紹了.NET中OpenFileDialog使用線程報錯的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • 詳解IIS在ASP.NET?Core下的兩種部署模式

    詳解IIS在ASP.NET?Core下的兩種部署模式

    ASP.NET?CORE應(yīng)用針對IIS具有兩種部署模式,它們都依賴于一個IIS針對ASP.NET?CORE?Core的擴展模塊,本文給大家介紹下IIS在ASP.NET?Core下的兩種部署模式,感興趣的朋友一起看看吧
    2022-03-03
  • ASP.NET 多次提交的解決辦法

    ASP.NET 多次提交的解決辦法

    只要把這2個方法放到頁面最下面(就是調(diào)用scriptmanager的RegisterStartupScript方法)
    2008-12-12
  • .Net?Core日志記錄之第三方框架Serilog

    .Net?Core日志記錄之第三方框架Serilog

    這篇文章介紹了.Net?Core日志記錄之第三方框架Serilog,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • .Net Core路由處理的知識點與方法總結(jié)

    .Net Core路由處理的知識點與方法總結(jié)

    這篇文章主要給大家介紹了關(guān)于.Net Core路由處理的知識點與方法的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • VS2017做為Unity3D的腳本編輯器需要的最精簡組件

    VS2017做為Unity3D的腳本編輯器需要的最精簡組件

    這篇文章主要為大家詳細介紹了VS2017做為Unity3D的腳本編輯器需要的最精簡組件,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • 未將對象引用設(shè)置到對象的實例 (System.NullReferenceException)

    未將對象引用設(shè)置到對象的實例 (System.NullReferenceException)

    System.NullReferenceException:未將對象引用設(shè)置到對象的實例,這是一個新鳥,中鳥,老鳥都避不開的錯誤
    2012-03-03
  • asp.net下的異步加載

    asp.net下的異步加載

    這篇文章主要為大家詳細介紹了asp.net的異步加載,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-08-08
  • 詳解ASP.NET MVC3:Razor的@:和語法

    詳解ASP.NET MVC3:Razor的@:和語法

    這篇文章主要介紹了詳解ASP.NET MVC3:Razor的@:和語法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01

最新評論

盐城市| 池州市| 新和县| 台州市| 商丘市| 迭部县| 桐梓县| 辰溪县| 阜平县| 福安市| 礼泉县| 遵义县| 太白县| 隆子县| 皮山县| 台东市| 娱乐| 齐齐哈尔市| 石门县| 濮阳县| 江阴市| 嘉义市| 拉萨市| 临沭县| 柞水县| 陆川县| 石景山区| 巴楚县| 双鸭山市| 张家口市| 益阳市| 正安县| 寻乌县| 隆化县| 正镶白旗| 翁源县| 金阳县| 朔州市| 宜宾市| 黎平县| 镇宁|