标签: entity-framework-core-3.1

Ambiguous call when using LINQ extension method on DbSet<T>

I am using a LINQ query on a DbSet<T>:

await _dbContext.Users.AnyAsync(u => u.Name == name);
Run Code Online (Sandbox Code Playgroud)

However, the compiler outputs the following error:

Error CS0121: The call is ambiguous between the following methods or properties:
'System.Linq.AsyncEnumerable.AnyAsync<TSource>(System.Collections.Generic.IAsyncEnumerable<TSource>, System.Func<TSource, bool>)' and
'Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AnyAsync<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource, bool>>)'
Run Code Online (Sandbox Code Playgroud)

A similar problem also occurs with other LINQ extension methods, like .Where().

I am using EF.Core 3.1 and have the System.Linq.Async package installed. How do I fix this issue?

c# linq ambiguous entity-framework-core entity-framework-core-3.1

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

在 ASP.NET Core 3.1 中设置值比较器

我在我的 DBContext 中使用了“HasConversion”来定义一个 JSonArray(语言/值)并将它保存为一个文本字段,它的作用就像一个魅力,我在我的解决方案中添加了一个新项目,没有任何改变,但后来我得到了添加有关“设置值比较器”的迁移的新错误。

我的模型是这样的:

    public class Brand
    {
        public int Id { get; set; }
        public new IList<LangValue> Name { get; set; } = new List<LangValue>();
    }
Run Code Online (Sandbox Code Playgroud)

DBContext就像:

    modelBuilder.Entity<Brand>(t =>
    {

        t.Property(p => p.Name).HasConversion(
            v => JsonConvert.SerializeObject(v, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include}),
            v => JsonConvert.DeserializeObject<IList<LangValue>>(v, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include})
         );
    });
Run Code Online (Sandbox Code Playgroud)

它运行良好,但在添加新项目后,我在添加迁移时出现黄色错误,并且模型未添加到新数据库中。

Microsoft.EntityFrameworkCore.Model.Validation[10620] 实体类型“品牌”上的属性“名称”是具有值转换器但没有值比较器的集合或枚举类型。设置值比较器以确保正确比较集合/枚举元素。

data-conversion dbcontext asp.net-core jsonconverter entity-framework-core-3.1

14
推荐指数
2
解决办法
6798
查看次数

尝试通过属性默认值更改关系时出现意外的 InvalidOperationException

在下面的示例代码中,我在执行以下操作时遇到以下异常db.Entry(a).Collection(x => x.S).IsModified = true

System.InvalidOperationException: '无法跟踪实体类型 'B' 的实例,因为另一个具有键值 '{Id: 0}' 的实例已被跟踪。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。

为什么不添加而不是附加 B 的实例?

奇怪的是,文档IsModified没有指定InvalidOperationException为可能的例外。无效的文档或错误?

我知道这段代码很奇怪,但我写它只是为了了解 ef core 在一些奇怪的 egde 情况下是如何工作的。我想要的是解释,而不是解决方法。

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public class A
    {
        public int Id { get; set; }
        public ICollection<B> S { get; set; } = new List<B>() { new B {}, new B {} };
    }

    public class B
    {
        public int Id { get; …
Run Code Online (Sandbox Code Playgroud)

c# language-lawyer entity-framework-core-3.1

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

EF Core:使用字典属性

有没有办法用 Entity Framework Core 填充字典属性?

出于性能原因,我们喜欢在应用程序而不是数据库中进行搜索。由于列表不能很好地扩展,我们喜欢使用字典。

例如(简化示例)

class Course
{
    public Dictionary<string, Person> Persons { get; set; }

    public int Id { get; set; }
}

class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情

  • 天真地只是添加一个字典属性。这将导致以下错误:

    System.InvalidOperationException:无法映射属性“Persons”,因为它属于“Dictionary”类型,它不是受支持的原始类型或有效的实体类型。显式映射此属性,或使用 '[NotMapped]' 属性或使用 'OnModelCreating' 中的 'EntityTypeBuilder.Ignore' 忽略它。

  • 尝试添加价值转换(使用HasConversion),但转换仅适用于单个项目而不适用于集合。在HasMany已经提供了一个编译错误:

    builder
      .HasMany<Person>(c => c.Persons) //won't compile, Persons isn't a IEnumerable<Person>
      .WithOne().HasForeignKey("PersonId");
    
    Run Code Online (Sandbox Code Playgroud)
  • 创建一个自定义集合类(从继承Collection<T>和实施InsertItemSetItem等等) -不幸的是,这也不会工作,因为EF核心将项目添加到集合和第一后,将填补特性(至少我们OwnsOne性质,即不在演示案例中) - …

c# dictionary entity-framework-core entity-framework-core-3.1

10
推荐指数
2
解决办法
7788
查看次数

Entity Framework Core 3.1 从存储过程返回值 (int)

这返回-1,我如何从存储过程中获取实际返回值?

这是我的存储过程

ALTER PROCEDURE [Production].[Select_TicketQuantity]
    @Ticket NVARCHAR(25),
    @Reference NVARCHAR(20)
AS
BEGIN

    declare @SQL nvarchar (4000)
    SET @SQL = 'select QARTCOL as Quantidade from D805DATPOR.GCARCCR1 where NCOLGIA = ' + @Ticket + ' AND NARTCOM = ''' + @Reference + ''''
    SET @SQL = N'select CONVERT(int,Quantidade) as Quantidade from OpenQuery(MACPAC, ''' + REPLACE(@SQL, '''', '''''') + ''')'
    PRINT @SQL
    EXEC (@SQL)

END   
Run Code Online (Sandbox Code Playgroud)

C# 代码

int? quantity= 0;
try
{
    quantity= await _context.Database.ExecuteSqlRawAsync("EXEC Production.Select_TicketQuantity @p0, @p1", parameters: new[] { ticket, reference});
} …
Run Code Online (Sandbox Code Playgroud)

c# sql-server entity-framework-core-3.1

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

在 EF Core 3.1 中加入群组

我正在尝试在 EF 核心 3.1 中分组加入它返回的问题

处理 LINQ 表达式 'DbSet 失败。这可能表明 EF Core 中存在错误或限制

我的代码是这样的

 var employees = await (from enrollment in RepositoryContext.Enrollments
                join allowance in RepositoryContext.Allowances.Include(y=>y.AllowanceType) on enrollment.EmployeeId equals allowance.EmployeeId
                    into allowances

                select new
                {
                    enrollment,
                    allowances

                }
            ).AsNoTracking().ToListAsync();
Run Code Online (Sandbox Code Playgroud)

津贴是项目的清单,有没有什么解决办法运行这样的,因为我需要它更好berformance查询。

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

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

在 FromSQL 查询和Where In 子句中使用整数参数数组

我有一个整数列表:

var ids = 新列表 { 10, 20 };

我需要找到具有该 id 的用户:

context.Users.FromSqlInterpolated($@" 
  select Users.* 
  where Users.Id in ({String.Join(',', ids)})"
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

'Conversion failed when converting the nvarchar value '10, 20' to data type int.'
Run Code Online (Sandbox Code Playgroud)

我该如何使用这样的参数?

linq-to-entities entity-framework-core entity-framework-core-3.1

8
推荐指数
2
解决办法
5747
查看次数

此平台不支持 Microsoft.Data.SqlClient - Entity Framework Core 3.1

Microsoft.EntityFrameworkCore.SqlServer在 .NET Core 3.1 库中使用 (3.1)。该库在运行时由可执行的 .NET Core 项目加载,方法是:

Assembly.LoadFrom('some.dll');
Run Code Online (Sandbox Code Playgroud)

当尝试从 a 检索数据时DbSet,出现以下异常:

System.PlatformNotSupportedException:“此平台不支持 Microsoft.Data.SqlClient。”

我猜这与运行时加载库有关,但我不明白为什么?

我尝试了各种不同的方法,例如Microsoft.Data.SqlClient使用版本 1.1 或 2.0 覆盖库,但没有成功。

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

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

没有 setter 的 Entity Framework Core 属性

在我的 .net core 3.1 应用程序中,我想将属性封装在某个实体中:

public class Sample : AuditableEntity
{
    public Sample(string name)
    {
        Name = name;
    }

    public int Id { get; }

    public string Name { get; }
}
Run Code Online (Sandbox Code Playgroud)

因此,我删除了所有公共设置器,因此当我想检查此类 Sample 是否已存在时,我的代码中的某个位置

_context.Samples.Any(r => r.Name == name)
Run Code Online (Sandbox Code Playgroud)

该行导致错误:System.InvalidOperationException: 'No suitable constructor found for entity type 'Sample'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'name' in 'Sample(string name)'.'

所以我添加了代码空构造函数

public class Sample : AuditableEntity
{ …
Run Code Online (Sandbox Code Playgroud)

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

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

EF Core 3.1 不允许对 Enum 属性进行 Contains 搜索

enum我正在尝试对我的属性进行包含搜索DbSet,EF Core 3.1 抛出以下错误

无法翻译 LINQ 表达式 'DbSet .Where(d => d.Position.ToString().Contains("acc"))'。以可翻译的形式重写查询,或者通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用来显式切换到客户端计算

实体:

public class DemoEntity
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Position Position { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

枚举 - 位置:

public enum Position
{
    [Display(Name = "Accountant")]
    Accountant,
    [Display(Name = "Chief Executive Officer (CEO)")]
    ChiefExecutiveOfficer,
    [Display(Name = "Integration Specialist")]
    IntegrationSpecialist,
    [Display(Name = "Junior Technical …
Run Code Online (Sandbox Code Playgroud)

c# enums entity-framework-core entity-framework-core-3.1

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