标签: ef-core-3.1

EF Core 3.1 / EF Core 5.0 中的 GroupBy 不起作用,即使是最简单的例子

我正在将 EF6.x 项目更新到 EF Core 3.1。决定回归基础并再次遵循如何从头开始建立关系的示例。

根据微软官方文档EF Core Relationship Examples,我将示例翻译成下面的控制台应用程序:

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlogPostsExample
{
    class Program
    {
        async static Task Main(string[] args)
        {
            // SQL Running in a Docker container - update as required
            var conString = "data source=localhost,14330;initial catalog=BlogsDb;persist security info=True;user id=sa;password=<Your super secure SA password>;MultipleActiveResultSets=True;App=EntityFramework;";

            var ctx = new MyContext(conString);

            await ctx.Database.EnsureCreatedAsync();

            var result = await ctx.Posts.GroupBy(p => p.Blog).ToArrayAsync();

        }
    }

    class MyContext : DbContext
    {
        private readonly string …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework group-by ef-core-3.1 ef-core-5.0

31
推荐指数
2
解决办法
8613
查看次数

EF Core 3.1 ExecuteSqlRaw / ExecuteSqlRawAsync 是 ExecuteSqlCommand / ExecuteSqlCommandAsync 的替代品吗?

升级到 EFCore 3.1 后出现不推荐使用的警告:

警告 CS0618 'RelationalDatabaseFacadeExtensions.ExecuteSqlCommandAsync(DatabaseFacade, RawSqlString, params object[])' 已过时:'对于使用纯字符串的 SQL 查询的异步执行,请改用 ExecuteSqlRawAsync。对于使用内插字符串语法创建参数的 SQL 查询的异步执行,请改用 ExecuteSqlInterpolatedAsync。

警告 CS0618 'RelationalDatabaseFacadeExtensions.ExecuteSqlCommand(DatabaseFacade, RawSqlString, params object[])' 已过时:'对于使用纯字符串执行 SQL 查询,请改用 ExecuteSqlRaw。要使用内插字符串语法执行 SQL 查询以创建参数,请改用 ExecuteSqlInterpolated。

它们相关的旧代码如下所示:

context.Database.ExecuteSqlCommand("DELETE FROM Table WHERE ID = @p0", id);
await context.Database.ExecuteSqlCommandAsync("DELETE FROM Table2 WHERE ID = @p0", id);
Run Code Online (Sandbox Code Playgroud)

查阅精美手册@somename根本没有讨论典型的 SQL Server 参数,实际上我什至看不到文档中的示例代码(它们显示在表名后打开括号)是有效的 SQL 语法:

context.Database.ExecuteSqlRaw("SELECT * FROM [dbo].[SearchBlogs]({0})", userSuppliedSearchTerm)
Run Code Online (Sandbox Code Playgroud)

我没有看到文档在哪里定义了userSuppliedSearchTerm变量的内容或其类型,我正在努力了解它如何成为一个明智的 SQL 块(string userSuppliedSearchTerm = "WHERE id = 123";带有烘焙值?SQL 注入?)或单个原始值( int userSuppliedSearchTerm = …

c# entity-framework-core ef-core-3.1

18
推荐指数
2
解决办法
3万
查看次数

Problem with EF OrderBy after migration to .net core 3.1

Consider this code:

_dbContext.Messages
    .GroupBy(m => new
        {
            MinId = m.SenderId <= m.RecipientId ? m.SenderId : m.RecipientId,
            MaxId = m.SenderId > m.RecipientId ? m.SenderId : m.RecipientId
        })
        .Select(gm => gm.OrderByDescending(m => m.SentAt).FirstOrDefault());
Run Code Online (Sandbox Code Playgroud)

By this I group all dialogues of users by their Id's no matter who sent the message. Then I order messages by SentAt date inside the groups and select one last message out of each dialogue. The thing is that this code worked and more over it translated …

c# linq-to-entities entity-framework-core .net-core-3.1 ef-core-3.1

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

如何在 EF Core 3.1 中以异步方式使用 GroupBy?

当我使用 GroupBy 作为对 EFCore 的 LINQ 查询的一部分时,出现错误System.InvalidOperationException: Client-side GroupBy is not supported

这是因为 EF Core 3.1 尝试尽可能多地在服务器端评估查询,而不是在客户端评估它们,并且调用无法转换为 SQL。

所以下面的语句不起作用,并产生上面提到的错误:

var blogs = await context.Blogs
    .Where(blog => blog.Url.Contains("dotnet"))
    .GroupBy(t => t.BlobNumber)
    .Select(b => b)
    .ToListAsync();
Run Code Online (Sandbox Code Playgroud)

现在显然解决方案是在调用 GroupBy() 之前使用 .AsEnumerable() 或 .ToList(),因为这明确告诉 EF Core 您想要进行分组客户端。在 GitHubMicrosoft 文档中对此进行了讨论。

var blogs = context.Blogs
    .Where(blog => blog.Url.Contains("dotnet"))
    .AsEnumerable()
    .GroupBy(t => t.BlobNumber)
    .Select(b => b)
    .ToList();
Run Code Online (Sandbox Code Playgroud)

然而,这不是异步的。我怎样才能使它异步?

如果我将 AsEnumerable() 更改为 AsAsyncEnumerable(),则会出现错误。如果我尝试将 AsEnumerable() 更改为 ToListAsync(),则 GroupBy() 命令将失败。

我正在考虑将它包装在 Task.FromResult …

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

13
推荐指数
2
解决办法
7315
查看次数

如何使用 EF 3.1 为实体框架 GroupBy 中的每个组选择前 N 行

我需要为带有实体框架的表中的每个组获取前 10 行。基于 SO 上的其他解决方案,我尝试了两件事:

var sendDocuments = await context.Set<DbDocument>
    .Where(t => partnerIds.Contains(t.SenderId))
    .GroupBy(t => t.SenderId)
    .Select(t => new
    {
        t.Key,
        Documents = t.OrderByDescending(t2 => t2.InsertedDateTime).Take(10)
    })                
    .ToArrayAsync();
Run Code Online (Sandbox Code Playgroud)

错误:

System.InvalidOperationException: 'The LINQ expression
'(GroupByShaperExpression: KeySelector: (d.SenderId), 
ElementSelector:(EntityShaperExpression: 
    EntityType: DbDocument
    ValueBufferExpression: 
        (ProjectionBindingExpression: EmptyProjectionMember)
    IsNullable: False ) )
    .OrderByDescending(t2 => t2.InsertedDateTime)' could not be translated. Either rewrite the query in a form that can be translated,
> or switch to client evaluation explicitly by inserting a call to
> either AsEnumerable(), AsAsyncEnumerable(), …
Run Code Online (Sandbox Code Playgroud)

entity-framework group-by entity-framework-core ef-core-3.1

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

Entity Framework Core 3.1 with NetTopologySuite.Geometries.Point: SqlException: 提供的值不是数据类型地理的有效实例

我有一个看起来像这样的模型:

public class Facility
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public NetTopologySuite.Geometries.Point Location { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

添加点的测试代码:

var testFacility = new Facility();
testFacility.Location = new NetTopologySuite.Geometries.Point(13.003725d, 55.604870d) { SRID = 3857 };

//Other values tested with the same error error

//testFacility.Location = new NetTopologySuite.Geometries.Point(13.003725d, 55.604870d);

//testFacility.Location = new NetTopologySuite.Geometries.Point(55.604870d, 13.003725d);

//var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 3857);
//var currentLocation = geometryFactory.CreatePoint(new Coordinate(13.003725d, 55.604870d));
//testFacility.Location = currentLocation;

db.Facilities.Add(testFacility);
//Exception on Save
db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

我正在使用以下 NuGets 版本 3.1.0

Microsoft.AspNetCore.Identity.EntityFrameworkCore …
Run Code Online (Sandbox Code Playgroud)

c# geospatial nettopologysuite entity-framework-core ef-core-3.1

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

.Net core 3.x Keyless Entity Types 避免表创建

我需要在实体框架核心 3.1.1 中执行一个复杂的 sql 查询,在研究中我发现无键实体类型是代码优先方法的方法。我看到很多关于 dbquery 的文档,但这在 .net core 3.x 中被标记为过时

无键实体类型

根据 Microsoft 文档,它说 dbquery 已过时,因此请改用 dbset 方法,但使用 dbset 它试图在数据库中创建一个新表。如何在应用迁移时禁用无键实体类型中的表生成?

示例代码

public class ApplicationContext : DbContext
{
 public DbSet<CustomQuery> CustomQuery { get; set; }
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
    modelBuilder.Ignore<CustomQuery>();
    modelBuilder.Entity<CustomQuery>().HasNoKey();
 }
}
Run Code Online (Sandbox Code Playgroud)

使用 .net 核心 2.2

var entity = _context.Query<CustomQuery>().FromSqlRaw(Regex.Unescape(selectQuery)).AsNoTracking().FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

使用 .net 核心 3.1

var newEntity = _context.CustomQuery.FromSqlRaw(Regex.Unescape(selectQuery)).AsNoTracking().FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

如果我尝试应用迁移,则会创建一个名为自定义查询的新表,但我不需要这种情况发生。因为这只是用于保存连接查询中的值的模型,我不会插入、更新或删除此表中的值。如何实现这一目标?

或者有没有更好的方法来解决这种情况。

c# entity-framework-core ef-core-3.0 ef-core-3.1

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

如何在存储库类中使用 IAsyncEnumerable

我正在使用 .net core 3.1 和 EF core 创建一个小型 API。
我尝试在我的存储库类中使用 IAsyncEnumerable 但出现错误。
我知道错误是有效的,但有人可以告诉我如何在存储库类中使用 IAsyncEnumerable 吗?

状态库.cs

    public class StateRepository : IStateRepository
    {
        public StateRepository(AssetDbContext dbContext)
            : base(dbContext)
        {

        }

        public async Task<State> GetStateByIdAsync(Guid id)
            => await _dbContext.States
                .Include(s => s.Country)
                .FirstOrDefaultAsync(s => s.StateId == id);

        public async IAsyncEnumerable<State> GetStates()
        {
            // Error says:
            //cannot return a value from iterator. 
            //Use the yield return statement to return a value, or yield break to end the iteration
             return await _dbContext.States
                       .Include(s => …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core-webapi c#-8.0 asp.net-core-3.1 ef-core-3.1

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

在同一项目中同时使用 AddDbContextFactory() 和 AddDbContext() 扩展方法

我正在尝试使用EF Core 文档的 DbContext 配置部分中DbContextFactory讨论的新模式。

我已经DbContextFactory在我的 Blazor 应用程序中成功启动并运行,但我想保留DbContext直接注入实例的选项,以保持我现有的代码正常工作。

但是,当我尝试这样做时,出现以下错误:

System.AggregateException:无法构造某些服务(验证服务描述符“ServiceType: Microsoft.EntityFrameworkCore.IDbContextFactory 1[MyContext] Lifetime: Singleton ImplementationType: Microsoft.EntityFrameworkCore.Internal.DbContextFactory1[MyContext]”时出错:无法使用范围服务“Microsoft.EntityFrameworkCore.DbContextOptions 1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory1[MyContext]”。) ---> System.InvalidOperationException:验证服务描述符“ServiceType:Microsoft.EntityFrameworkCore.IDbContextFactory 1[MyContext] Lifetime: Singleton ImplementationType: Microsoft.EntityFrameworkCore.Internal.DbContextFactory1[MyContext]”时出错:无法使用范围服务“Microsoft.EntityFrameworkCore.DbContextOptions 1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory1[MyContext]”。---> System.InvalidOperationException:无法使用范围服务“Microsoft.EntityFrameworkCore.DbContextOptions 1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory1[MyContext]”。

在试验时,我还设法在某一时刻得到了这个错误:

无法从根提供程序解析范围服务“Microsoft.EntityFrameworkCore.DbContextOptions`1[MyContext]”。

它是理论上可以同时使用AddDbContextAddDbContextFactory在一起?

c# entity-framework dependency-injection ef-core-3.1 ef-core-5.0

11
推荐指数
3
解决办法
3425
查看次数

Entity Framework creates migration without any updates

At the moment, I'm experiencing an issue where I can create a migration, which has data updates, but the DbContextModelSnapshot has this data. When you look at the updates in the migration, they've already been applied to the DbContextModelSnapshot and the database.

A coworker created a migration about 3 months ago, and everything has been fine. We've created several more migrations since then, and haven't experienced this issue. However, the last couple days, we have been experiencing this.

We've tried …

c# entity-framework-core entity-framework-migrations ef-core-3.1

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