标签: ef-core-2.1

实体框架核心数据库表值函数映射

我使用EFCore 2.1数据库优先方法。我非常熟悉 SQL 语法,更喜欢自己构建查询,而不是将这项工作留给 EF。我使用表值函数和标量函数来查询数据库。

我为标量找到了这个

https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0#database-scalar-function-mapping

但不幸的是没有关于函数。

当我运行 Scaffolding 时,有没有办法强制 Visual Studio 从 SQL Server 中获取所有表函数和标量函数和存储过程?

我以前使用 LINQ to SQL dbml设计器。使用dbml一切都非常简单。您从服务器资源管理器拖放到dbml和繁荣,我可以像常规 C# 方法一样使用 SQL 函数或 SP。

在此处输入图片说明

有机会在 EFCore 中重现这个吗?

stored-procedures user-defined-functions ef-core-2.1

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

如何从 Dotnet EF 中删除唯一索引?

我有一个模型:

用户

public class User {
 public int Id { get; set; }
 public string UserName {get; set;}
 ...
 public int? ManagerId {get; set;}
 public User Manager {get; set;}
 public int? SupervisorId {get; set;}
 public User Supervisor {get; set;}
..
}
Run Code Online (Sandbox Code Playgroud)

我检查了我的 MySQL Db,发现 ManagerId 是唯一的。我没有将其设置为唯一。现在我想使用 dotnet ef 迁移删除它。怎么做 ?

我现在使用 donet core 2.1。

我已经测试删除 ManagerID 和 Manager 并执行 dotnet ef 迁移添加 UpdateUser

检查并删除 ManagerID。然后我尝试再次添加新名称AssignedManagerID,它创建了一个新名称,且unique为true。

migrationBuilder.CreateIndex(
                name: "IX_Users_AssignedManagerId",
                table: "Users",
                column: "AssignedManagerId",
                unique: true);
Run Code Online (Sandbox Code Playgroud)

我的 Datacontext:公共 DbSet 用户 {get; 放;} …

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

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

EF Core 在迁移过程中锁定数据库

运行迁移时是否可以从任何其他连接锁定数据库Database.Migrate()

我们有多个服务实例运行相同的代码(在 AWS Lambda 上),并在启动时进行迁移。现在,当我们想要应用一些迁移时,我们必须手动确保只有一个实例正在运行,否则他们都可以尝试这样做并破坏事情。

是否有数据库级别的解决方案?

ef-core 2.1

entity-framework-core .net-core ef-core-2.1

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

为什么在 asp .net core 2.1 中的每次迁移时都会删除种子角色?

我在每次迁移时都会遇到种子角色的奇怪行为。无论您做了什么更改,迁移都会删除种子角色并再次插入它们。当项目中没有进行任何修改时,将创建下面给出的迁移。

所有其他模型均已正确播种,并且仅在修改它们时才考虑迁移。

我将 ASP .NET Core 2.1 与个人身份验证一起使用

用于播种的 DbContext 类

 public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        #region Seed-Roles

        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "SuperAdmin", NormalizedName = "SuperAdmin".ToUpper() });
        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Owner", NormalizedName = "Owner".ToUpper() });
        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin", NormalizedName = "Admin".ToUpper() });
        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Tester", NormalizedName = "Tester".ToUpper() });
        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "User", NormalizedName …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core-identity asp.net-core-2.1 ef-core-2.1 entity-framework-migrations

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

HasDefaultValue 与从构造函数设置默认值

使用 EF Core 时,我们可以设置属性的默认值。

public class Foo
{
    public int Bar { get; set; }
}

public class FooConfiguration : IEntityTypeConfiguration<Foo>
{
    public void Configure(EntityTypeBuilder<Foo> builder)
    {
        builder.Property(s => s.Bar).HasDefaultValue(1337);
    }
}
Run Code Online (Sandbox Code Playgroud)

我们什么时候应该更喜欢使用HasDefaultValue类中的默认值而不是初始化类内的默认值?

public class Foo
{
    public int Bar { get; set; } = 1337;

    // or inside constructor...
    // public Foo { Bar = 1337; }
}
Run Code Online (Sandbox Code Playgroud)

或者我们应该两者都做?但在这种情况下,HasDefaultValue似乎是多余的。这似乎是一个只能选择 1 个选项的选择。

c# entity-framework-core ef-core-2.1

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

EF Core 延迟加载速度极慢

我做了一个小测试,启用惰性loading.optionsBuilder.UseLazyLoadingProxies().UseSqlServer(ConnectionString);

(使用 EF Core 2.1.4)

我循环浏览有和没有的仪器,这是我得到的结果

情况1

var instruments = db.instruments.OrderBy(t=>t.id).Include(t=>t.NavPro1).ThenInclude(t=>t.NavPro2).Take(200);
Run Code Online (Sandbox Code Playgroud)

案例2

var instruments = db.instruments.OrderBy(t=>t.id).Include(t=>t.NavPro1).ThenInclude(t=>t.NavPro2).Take(200);
Run Code Online (Sandbox Code Playgroud)

然后

   foreach (var i in instruments)
   {
        var props = i.NavPro1;
        foreach (var prop in props)
        {
            sbPrintGreeks.AppendLine(prop.NavPro2.Name + " - " + prop.id + " - " + prop.Value);
        }
   }
Run Code Online (Sandbox Code Playgroud)

无需延迟加载,只需 7 秒即可获取 100k 行

使用延迟加载需要 160 秒才能获取 3k 行。

可以做些什么来获得良好的性能?

c# ef-core-2.1

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

如何使用 EF Core 在列表中选择不在表中的值?

我有一个相当大的字符串列表(30k+),我需要使用 Entity Framework Core 检查表中不存在哪些字符串。

像这样但没有发送每个项目的请求来检查:

var notFoundItems = hugeList.Where(c => !tableToCheck.Any(x => x.Id == c)).ToList();
Run Code Online (Sandbox Code Playgroud)

我找到了答案,但使用T-SQL

c# linq entity-framework entity-framework-core ef-core-2.1

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

EF Core - 在上一个操作完成之前,在此上下文中启动了第二个操作。不保证任何实例成员都是线程安全的

我正在使用EF Core 2.1并且我正在尝试使用Tasks(TPL)一次性更新多个实体:

public async Task UpdateAttendance(IEnumerable<MyEvents> events)
{
    try
    {
        var tasks = events.Select(async entity =>
        {
            await Task.Run(() => Context.Entry(entity).Property(x => x.Attendance).IsModified = true);
            await Context.SaveChangesAsync();
        });

        await Task.WhenAll(tasks);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message ?? ex.InnerException.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

但这会引发以下错误。

在前一个操作完成之前,在此上下文中启动了第二个操作。不保证任何实例成员都是线程安全的。

启动文件

services.AddScoped<IMyRepository, MyRepository>();
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

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

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

EF 核心 QueryFilter 的性能问题

在我们的系统中,我们在 EF 核心中使用 QueryFilters 时遇到了性能问题。问题在于 EF 核心过滤器在 LEFT JOIN 内部进行过滤,而不是在其外部进行过滤。

生成的 SQL 看起来像这样:

SELECT [pom].[Id],
        [pom].[DeleteDate],
        [pom].[UpdateDate],
        [pom].[Version],
        [t].[Id],
        [t].[MandatorId],
        [t].[NetPriceAmount],
        [t].[NetPriceCurrencyIso4217Code]
FROM [externaldata].[PurchaseOfferMetadata] AS [pom]
    LEFT JOIN (
    SELECT [po].[Id],
            [po].[MandatorId],
            [po].[NetPriceAmount],
            [po].[NetPriceCurrencyIso4217Code]
    FROM [externaldata].[PurchaseOffer] AS [po]
    WHERE [po].[MandatorId] = 1
) AS [t] ON [pom].[Id] = [t].[Id]
WHERE [pom].[Id] IN 
    (CAST(3094411 AS bigint), 
    CAST(4757070 AS bigint), 
    CAST(4757112 AS bigint), 
    CAST(5571232 AS bigint))
Run Code Online (Sandbox Code Playgroud)

有问题的部分是WHERE [po].[MandatorId] = 1. 如果这是在第二个WHERE语句中,则查询运行得更快。

数据库模型配置如下:

modelBuilder.Entity<PurchaseOffer>()
      .HasQueryFilter(po => po.MandatorId == 1) …
Run Code Online (Sandbox Code Playgroud)

c# sql entity-framework ef-core-2.0 ef-core-2.1

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

EFCore FromSql 异步

我想并行执行几个 SELECT 存储过程调用。我设置我的上下文如下:

public virtual DbSet<Task<GetCaseCaseContextModel>> CaseGetCaseContextData { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后我的 repo 类执行以下操作:

public async Task<List<GetCaseNotesContextModel>> GetCaseNotes(string caseId)
{
    var notes = _context.CaseGetCaseContextData.FromSql("x_Fortellis_CaseGetCaseNotes @p0", caseId, caseId).ToListAsync();

    return notes;
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

严重性代码描述项目文件行抑制状态错误CS0029无法隐式转换类型'System.Threading.Tasks.Task<System.Collections.Generic.List<System.Threading.Tasks.Task<CaseManagement.Infrastruct.Database.Repo.Case.GetCase .GetCaseCaseContextModel>>>' 到 'System.Collections.Generic.List<CaseManagement.Infrastruct.Database.Repo.Case.GetCase.GetCaseNotesContextModel>' CaseManagement.Infrastruct.Database C:\Dev\Bitbucket\webscv\Fortellis\CaseManagement\CaseManagement .Infrustruct.Database\Repo\Case\GetCase\GetCaseRepoHelper.cs 72 活动

当我将上下文更改为:

public virtual Task<DbSet<GetCaseCaseContextModel>> CaseGetCaseContextData { get; set; }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

严重性代码说明项目文件行抑制状态错误 CS1061“Task<DbSet>”不包含“FromSql”的定义,并且找不到接受类型“Task<DbSet>”的第一个参数的可访问扩展方法“FromSql”(是您缺少 using 指令或程序集引用吗?) CaseManagement.Infrastruct.Database C:\Dev\Bitbucket\webscv\Fortellis\CaseManagement\CaseManagement.Infrustruct.Database\Repo\Case\GetCase\GetCaseRepoHelper.cs 70 活动

我最终想使用以下方式致电他们:

GetCaseCaseContextModel caseData = new GetCaseCaseContextModel();
List<GetCaseNotesContextModel> notes = new List<GetCaseNotesContextModel>();

Parallel.Invoke(
    async () => caseData = await GetCaseData(caseId, dealerGroupId),
    async () …
Run Code Online (Sandbox Code Playgroud)

entity-framework-core ef-core-2.0 ef-core-2.1

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