小编Hec*_*res的帖子

.net Core 2、EF 和多租户 - 基于用户的 Dbcontext 切换

我有(几乎)最糟糕的多租户。我正在构建一个 asp.net 核心网站,我正在将一堆 pokey 小 Intranet 网站移植到该网站。每个子站点将是一个 asp.net 区域。我有一个IdentityContext身份的东西。我有多个供应商数据库副本,每个副本都有多个租户。该ApplicationUser班有,我想用切换分贝范围内的OrgCode财产。

我可以看到自己需要将 User.OrgCode 和 Area 映射到连接字符串的东西

Stack Overflow 上有很多这方面的部分示例。一个下午的阅读后,我很困惑。它的核心接缝是:

  • 从构造函数参数中删除 DI dbcontext ref。
  • 在控制器构造函数中实例化 dbcontext。
  • 像以前一样使用 dbcontext。

我在正确的轨道上吗?

有什么连贯的例子吗?


编辑 2020/07/09

不幸的是,这变得更加紧迫。

身份数据库与租户无关。Identity 中的每个用户都有一个 OrgCode 标识符。(自定义用户属性)。

每个服务器都通过使用“成本中心”内置了多租户。服务器在每台服务器上都有一组名称相同的数据库。

  1. 核心供应商数据库
  2. 我们存储扩展的自定义数据库
  3. 用于我们的作业输出的日志数据库

还有一些小型应用程序特定数据库已经使用组织代码来识别用户

服务器 A - 1 组织代码

服务器 B - 4 个组织代码

服务器 C - 3 个组织代码参与项目,50+ 还没有(大部分很小)

服务器 D - 目前没有使用组织代码。服务器上 80+。(很快)

不可能将所有组织合并到一台服务器上。存在法律和技术后果。每个服务器都有数百个远程转发器向它们报告需要更新。这些提供的数据是我们的自定义作业使用的数据。

梦想是继续在每个页面中使用 DI,根据需要传入上下文。然后上下文将足够智能,可以根据用户名的 OrgCode 选择正确的底层连接详细信息。

我对使用代理这个词犹豫不决,因为它在这个空间中似乎负载很重。

地狱,如果我知道把它放在哪里,即使使用 switch 语句也很好

预期效果来自 Org XYZ 的用户加载需要供应商数据库的页面,他们从 XYZ 映射到的服务器获取该页面。 …

c# entity-framework dbcontext asp.net-core

11
推荐指数
2
解决办法
1241
查看次数

EF核心和多个数据库

我有一个带有三个数据库的旧系统

  1. 供应商
  2. 自定义代码
  3. 日志数据

供应商包含来自我们的供应商应用程序的控制和日志数据。

CustomCode包含许多连接到Vendor和LogData的视图和存储过程

LogData包含我们CustomCode流程的结果。例如:每日/每周/每月摘要和结果。

我正在写一个将在地图上绘制数据的网站。单位列表来自CustomCode中的视图。摘要记录来自LogData,而单个日志点则通过CustomCode中存储的proc从供应商处检索。

我从用于CustomCode的DbContext开始,但是似乎无法导航到LogData的第二个DbContext中的属性。

我可以在不同上下文中的对象之间链接导航属性吗?

我可以一次连接多个数据库吗?

请注意,这与多租户或多模式无关

c# entity-framework-core asp.net-core

7
推荐指数
1
解决办法
4896
查看次数

MVC JsonResult有数据,但浏览器没有数据

我有控制器方法GetLayer2()。它与GetLayer0()和GetLayer1()非常相似

[HttpGet]
public async Task<JsonResult> GetLayer2(string datePassedIn, string eventType, string driverId)
{
    string orgCode = "HVO"; //User.Identity.GetOrgCode();
    DateTime? processDate;
    DateTime defaultDate = DateTime.Today.AddDays(-1);  //default yesterday 

    if (String.IsNullOrEmpty(datePassedIn))
    {
        _logger.LogError(String.Format("Date passed in was NULL or empty. Using default date {0}", defaultDate.ToString(inputDateFormat)), null);
        processDate = defaultDate;
    }
    else
    {
        try
        {
            processDate = DateTime.ParseExact(datePassedIn, inputDateFormat, cultureProvider);
        }
        catch (FormatException ex)
        {
            _logger.LogError(ex, "Error formatting date {datePassedIn} did not match {inputDateFormat}. using default date {defaultDate}", null);
            processDate = defaultDate;
        }
    }

    driverId = …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc json asp.net-core

7
推荐指数
1
解决办法
196
查看次数

由于InverseProperty模型而导致Asp.net Core 2.1崩溃

在第一次调用DbContext时,System.Reflection中一个非常长的未处理异常导致我的网站在加载时崩溃。

使用ef-core 2.1 rc1

System.ArgumentNullException: Value cannot be null.
Parameter name: type
   at System.Reflection.IntrospectionExtensions.GetTypeInfo(Type type)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.InversePropertyAttributeConvention.ConfigureInverseNavigation(InternalEntityTypeBuilder entityTypeBuilder, MemberInfo navigationMemberInfo, InternalEntityTypeBuilder targetEntityTypeBuilder, InversePropertyAttribute attribute)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.InversePropertyAttributeConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder, PropertyInfo navigationPropertyInfo, Type targetClrType, InversePropertyAttribute attribute)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.NavigationAttributeEntityTypeConvention`1.Apply(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.RunVisitor.VisitOnEntityTypeAdded(OnEntityTypeAddedNode node)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnEntityTypeAddedNode.Accept(ConventionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionVisitor.Visit(ConventionNode node)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionVisitor.VisitConventionScope(ConventionScope node)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Run()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Dispose()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.RelationshipDiscoveryConvention.DiscoverRelationships(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.RelationshipDiscoveryConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.AddEntityType(EntityType entityType)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.AddEntityType(Type type, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(TypeIdentity& type, ConfigurationSource configurationSource, …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework-core asp.net-core-2.0 ef-core-2.0

6
推荐指数
2
解决办法
902
查看次数

用 TSQL 替换字符串中的每个第二个字符实例

我有一个字段,其中包含定义地理围栏(多边形)的纬度/经度坐标字符串。每个都用逗号分隔。

例如:'纬度,经度,纬度,经度,纬度,经度'
例如:148.341158,-21.500773,148.341406,-21.504989,148.375136,-21.513174,148.401674,-21.535247,148.418044,-21.53 2767,148.408867,-21.511685,148.414075,- 21.508461,148.36968,-21.432567,148.349094,-21.438768,148.346862,-21.480187,148.341158,-21.500773,

我想将其与 MSSQL 中的地理类型一起使用(http://msdn.microsoft.com/en-us/library/bb933971.aspx

DECLARE @g geography;
SET @g = geography::STPolyFromText('POLYGON((-122.358 47.653, -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326);
SELECT @g.ToString();
Run Code Online (Sandbox Code Playgroud)

这似乎需要:“lat long,lat long,lat long”,即:一对之间没有逗号。

我无法更改源数据,因为它由供应商程序使用。我需要操作字符串以删除每 2 个逗号中的 1 个,或者如果失败,请在 TSQL 中使用正则表达式

regex t-sql sql-server replace

5
推荐指数
1
解决办法
4169
查看次数

ApplicationUser类型不能在泛型类型或方法'IdentityDbContext <TUser>中用作类型参数'TUser'

尝试在ASP.NET Core 2.0中实现Identity.我遇到很多问题.

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("Ctrack6_Custom"))
        );


        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

etc...
Run Code Online (Sandbox Code Playgroud)

ApplicationUser.cs使用Guid作为密钥.同时设置角色等

// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser<Guid>
{
    [MaxLength(50)]
    public string FirstName { …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-identity asp.net-core-2.0

5
推荐指数
1
解决办法
3895
查看次数

配置 Serilog.Extensions.Logging.File

按照Nicholas Blumhardt 页面和后来的Serilog github 页面上的说明,我在让 Serilog 工作时遇到了问题。具体来说

错误 CS1061“ILoggerFactory”不包含“AddFile”的定义,并且找不到接受“ILoggerFactory”类型的第一个参数的扩展方法“AddFile”(您是否缺少 using 指令或程序集引用?)

我已经从 NuGet 下载了最新的包。我的 .proj 有以下条目<PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2" />

安装后我重新启动了 Visual Studio。

Startup.cs(第一次)

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddFile("Logs/app-{Date}.txt");
Run Code Online (Sandbox Code Playgroud)

Program.cs(第 2 节)

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((hostingContext, builder) =>
        {
            builder.AddFile("Logs/myapp-{Date}.txt");
        })
        .UseStartup<Startup>();
Run Code Online (Sandbox Code Playgroud)

更糟糕的是,我一年多前为一个项目做了这个,相比之下,我看不出我做错了什么:(

c# logging serilog asp.net-core

4
推荐指数
1
解决办法
6097
查看次数

使用 powershell 将整数存储在自定义对象中

我喜欢在 powershell 中使用如下所示的结构。它们使跟踪 6 个月后发生的事情变得更加容易。

$processConfig = New-Object -TypeName psobject
$processConfig | Add-Member -MemberType NoteProperty -Name StartDate -Value ($startofweek)
$processConfig | Add-Member -MemberType NoteProperty -Name StartDateStr -Value (Get-Date $processConfig.StartDate -Format "yyyyMMdd HH:mm:ss")
$processConfig | Add-Member -MemberType NoteProperty -Name EndDate -Value ($endofweek)
$processConfig | Add-Member -MemberType NoteProperty -Name EndDateStr -Value (Get-Date     $processConfig.EndDate -Format "yyyyMMdd HH:mm:ss")
$processConfig | Add-Member -MemberType NoteProperty -Name TargetDir -Value  "C:\Scripts\out\"

$dbConfig = New-Object -TypeName psobject
$dbConfig | Add-Member -MemberType NoteProperty -Name Server -Value "server.address"
#etc
Run Code Online (Sandbox Code Playgroud)

但是,我一生都无法弄清楚如何将普通 int …

powershell types object

4
推荐指数
1
解决办法
3584
查看次数

使用 asp-page TagHelper 时链接不呈现

我有一个页面在使用asp-page TagHelper时不会在 HTML 中呈现链接。我以前见过这个,但这是由于打字错误或页面不存在。

在下面 _Layout 中的两个链接中,

  • 用户呈现为 http://localhost/ReportGroups/Admin/Users
  • 角色呈现为 http://localhost/ReportGroups
  • 手动导航到角色会导致 404 错误。

_Layout.cshtml

该链接是管理菜单的一部分。注释掉的 FontAwesome 图标是我测试的一部分。 /Admin/Users工作正常,但/Admin/RoleList不起作用。以前是这样,/Admin/Roles但我分部分构建了该文件的新副本,以查看是否有任何内容引发错误,或者它是否是保留字。

@if (User.Identity.IsAuthenticated)
{
    if (User.IsInRole("Admin"))
    {
        <div id="nav-admin">
            <ul>
                <li><a asp-page="/Admin/Users"> Users</a></li>@*< i class="fas fa-user-secret" title="Users"></i>*@
                <li><a asp-page="/Admin/RoleList"> Roles</a></li>
                @*<i class="fas fa-id-card" title="Roles"></i>*@
            </ul>
        </div>
    }
}
Run Code Online (Sandbox Code Playgroud)

角色列表.cshtml

@page "{roleId}/{userId}"
@model RoleListModel
@{
    ViewData["PageTitle"] = "Admin Tools - Roles";
    ViewData["IconClass"] = "";
    ViewData["IconTitle"] = "Roles";
}

<table>
    <thead>
        <tr>
            <th>Role</th>
            <th>User Name</th>
            <th>First Name</th>
            <th>Last …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core-2.0 asp.net-core-tag-helpers razor-pages

3
推荐指数
4
解决办法
6631
查看次数

Asp.Net Core 2绑定对象为null

当我提交表单时,ModelValidation.IsValid 为 true,但我使用的 [BindProperty] 对象为 null。

页面模型

[BindProperty]我在房产上有标签public Group Group {get; private set}

在该OnGetAsync(int? Id)方法中,我查找组并.FindAsync(Id)填充表单。效果很好:)

我的理解是,OnPostAsync()由于 BindProperty 注释,应该自动填充 Group 对象。但是,一旦我发布 ModelState 有效,但 Group 对象为空。我该如何解决?

using xxx.ReportGroups.Data;
using xxx.ReportGroups.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace xxx.ReportGroups.Pages
{

    public class GroupEditModel : PageModel
    {
        private readonly ApplicationDbContext _db;

        public GroupEditModel(ApplicationDbContext db)
        {
            _db = db;
        }

        [BindProperty]
        public string ErrorMessage { get; …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core-2.0 razor-pages

1
推荐指数
1
解决办法
1599
查看次数