我正在将 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) 升级到 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 = …
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
当我使用 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 您想要进行分组客户端。在 GitHub和Microsoft 文档中对此进行了讨论。
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 …
我需要为带有实体框架的表中的每个组获取前 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) 我有一个看起来像这样的模型:
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
我需要在实体框架核心 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)
如果我尝试应用迁移,则会创建一个名为自定义查询的新表,但我不需要这种情况发生。因为这只是用于保存连接查询中的值的模型,我不会插入、更新或删除此表中的值。如何实现这一目标?
或者有没有更好的方法来解决这种情况。
我正在使用 .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) 我正在尝试使用EF Core 文档的 DbContext 配置部分中DbContextFactory
讨论的新模式。
我已经DbContextFactory
在我的 Blazor 应用程序中成功启动并运行,但我想保留DbContext
直接注入实例的选项,以保持我现有的代码正常工作。
但是,当我尝试这样做时,出现以下错误:
System.AggregateException:无法构造某些服务(验证服务描述符“ServiceType: Microsoft.EntityFrameworkCore.IDbContextFactory
1[MyContext] Lifetime: Singleton ImplementationType: Microsoft.EntityFrameworkCore.Internal.DbContextFactory
1[MyContext]”时出错:无法使用范围服务“Microsoft.EntityFrameworkCore.DbContextOptions1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory
1[MyContext]”。) ---> System.InvalidOperationException:验证服务描述符“ServiceType:Microsoft.EntityFrameworkCore.IDbContextFactory1[MyContext] Lifetime: Singleton ImplementationType: Microsoft.EntityFrameworkCore.Internal.DbContextFactory
1[MyContext]”时出错:无法使用范围服务“Microsoft.EntityFrameworkCore.DbContextOptions1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory
1[MyContext]”。---> System.InvalidOperationException:无法使用范围服务“Microsoft.EntityFrameworkCore.DbContextOptions1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory
1[MyContext]”。
在试验时,我还设法在某一时刻得到了这个错误:
无法从根提供程序解析范围服务“Microsoft.EntityFrameworkCore.DbContextOptions`1[MyContext]”。
它是理论上可以同时使用AddDbContext
和AddDbContextFactory
在一起?
c# entity-framework dependency-injection ef-core-3.1 ef-core-5.0
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
ef-core-3.1 ×10
c# ×9
ef-core-5.0 ×2
group-by ×2
asp.net-core ×1
c#-8.0 ×1
ef-core-3.0 ×1
entity-framework-migrations ×1
geospatial ×1