实体框架(EF)Core是由Microsoft开发的开源ORM。
我有两个具有这种结构的实体: 公共抽象类 BaseEntity { 公共基础实体() { //证实(); } 公共 Guid Id { 获取;放; } = Guid.NewGuid(); 公开
我开发了一个 Azure Function 应用程序,通过 EF Core 8 连接到 Azure SQL Server。我使用系统分配的标识。 当连接到桌子等时,一切都会按预期进行。但当我...
Ef core 是否会在加载 .Include 中的实体之前加载实体的所有属性?
我有一个实体,我拥有一个依赖于虚拟成员的属性。加载实体时,我将虚拟成员设置为 null,即使我已将其包含在 .Include 中。 我的实体
EF Core ManyToMany Join Table 具有相同模型关系,级联删除行为问题
具有两个相同实体的联接表保存这些实体的关系。问题是外键约束阻止级联删除行为,这是我所需要的
我最近将运行 Entity Framework Core 2.1.1 的应用程序升级到 Entity Framework Core 7.0.11。 以下代码部分 (C#) 在旧版本中运行良好: var items = _dbContext.
这可能是一个愚蠢的问题,但 EF Core 似乎没有 Get-Migrations 命令。是无论如何都被更换了还是微软只是决定不需要它?
我有一个在运行时创建表的方法: 公共异步任务CreateTable(字符串表名,IEnumerable列) { var columnsString = string.Join(", &qu...
我正在使用 EFCore 7.0 和 Pomelo 7.0 以及 MySQL 8.0。当我在 NetCore 项目中执行原始 SQL 时,出现错误。这是以前版本中的工作方式。 代码是: var cnt = context.Database.SqlQu...
考虑以下模型类: 公共抽象类A { 公共枚举 T { B_, C_, D_ } 公共 int Id { 得到;放; } 公共整数?父级 ID { 获取;放; } 公共A?父级 { 得到; ...
我有一个通过 Nuget 提供给我的课程。我没有来源。 公共类 SpecialProductResult { 公共 int id { 得到;放; } 公共小数 SpecialPercent {get;set;} } 我想要
我有一个从实体框架软件模型到 SoftwareDTO 的映射设置,当我像这样投影到它时,它可以正常工作: var stuff =等待ChecklistLink.AsNoTracking() .S...
我是 DI 新手,遇到了问题。我正在制作一个使用本地 postgreSQL 数据库的 Avalonia 应用程序(C#)。注册应用程序时,它会同时检查电子邮件和用户名是否...
C# 和 EntityFramworkCore:运行“$ dotnet ef 数据库更新”后出错。:对象引用未设置到对象的实例
我正在使用数据库实体框架构建一个网站,在简单地重命名一个字段并删除另一个字段后出现此错误 这是最后添加的迁移: 使用微软。
使用 postgresql 查询数据时未使用 Entity Framework Core `HasConversion` 属性配置
我通过 Npgsql 将实体框架与 Postgre 一起使用,映射到 Cashouts 表的 Cashout 类型配置的一部分涉及: 公共无效配置(EntityTypeBuilder 我通过 Npgsql 将实体框架与 Postgre 结合使用,映射到 Cashout 表的 Cashouts 类型配置的一部分涉及: public void Configure(EntityTypeBuilder<Cashout> builder) { builder.ToTable("Cashouts"); builder.ConfigureGuidEntity(); builder.Property(c => c.RecipientAccountId).IsRequired(); builder.Property(c => c.State).IsRequired().HasConversion( v => v!.Name, v => Enumeration.FromDisplayName<CashoutState>(v)); builder.HasIndex(e => e.State); builder.HasIndex(e => e.RecipientAccountId); builder.UseXminAsConcurrencyToken(); } Cashout类型定义如下: public class Cashout : GuidEntity { public int RecipientAccountId { get; set; } public string? RecipientAccountName { get; set; } public decimal Amount { get; set; } public string? Comment { get; set; } public CashoutState? State { get; set; } = CashoutState.Pending; public string? Reason { get; set; } public Cashout() { } public Cashout(Guid id) : base(id) { } } 并继承自 GuidEntity 类型: public abstract class GuidEntity : Entity<Guid> { protected GuidEntity() { Id = Guid.Empty; } protected GuidEntity(Guid id) { Id = id; } public DateTimeOffset CreatedOn { get; private set; } = DateTimeOffset.UtcNow; public DateTimeOffset? UpdatedOn { get; private set; } } 本身继承自Entity: public abstract class Entity<TKey> : IEntity<TKey>, IEquatable<Entity<TKey>> where TKey: struct { private readonly Lazy<int> _requestedHashCode; private readonly Lazy<int> _requestedTransientHashCode; public virtual TKey Id { get; protected set; } protected Entity() { _requestedHashCode = new Lazy<int>(() => Id.GetHashCode() ^ 31); _requestedTransientHashCode = new Lazy<int>(() => Guid.NewGuid().GetHashCode()); } public bool IsTransient() => EqualityComparer<TKey>.Default.Equals(Id, default); public override bool Equals(object obj) => Equals((obj as Entity<TKey>)!); public bool Equals(Entity<TKey> other) { if (other == null) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.IsTransient() || this.IsTransient()) { return false; } return EqualityComparer<TKey>.Default.Equals(other.Id, Id); } public override int GetHashCode() => IsTransient() ? _requestedTransientHashCode.Value : _requestedHashCode.Value; } State属性的类型是CashoutState: public abstract class CashoutState : Enumeration { public static CashoutState Transferred = new TransferredCashoutState(); public static CashoutState TransferFailed = new TransferFailedCashoutState(); public static CashoutState Withdrawn = new WithdrawnCashoutState(); public static CashoutState WithdrawalFailed = new WithdrawalFailedCashoutState(); public static CashoutState Pending = new PendingCashoutState(); public static CashoutState Cancelled = new CancelledCashoutState(); protected CashoutState(int id, string name) : base(id, name) { } private class TransferredCashoutState : CashoutState { public TransferredCashoutState() : base(1, nameof(Transferred)) { } } private class WithdrawnCashoutState : CashoutState { public WithdrawnCashoutState() : base(2, nameof(Withdrawn)) { } } private class WithdrawalFailedCashoutState : CashoutState { public WithdrawalFailedCashoutState() : base(3, nameof(WithdrawalFailed)) { } } private class TransferFailedCashoutState : CashoutState { public TransferFailedCashoutState() : base(4, nameof(TransferFailed)) { } } private class PendingCashoutState : CashoutState { public PendingCashoutState() : base(5, nameof(Pending)) { } } private class CancelledCashoutState : CashoutState { public CancelledCashoutState() : base(6, nameof(Cancelled)) { } } } 然后还有 Enumeration 类型的另一位继承: public abstract class Enumeration : IComparable { public string Name { get; private set; } public int Id { get; private set; } protected Enumeration(int id, string name) { Id = id; Name = name; } public override string ToString() => Name; public static IEnumerable<T> GetAll<T>() where T : Enumeration => typeof(T) .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) .Select(f => f.GetValue(null)).Cast<T>(); public override bool Equals(object obj) { if (!(obj is Enumeration otherValue)) return false; var typeMatches = GetType() == obj.GetType(); var valueMatches = Id.Equals(otherValue.Id); return typeMatches && valueMatches; } public override int GetHashCode() => Id.GetHashCode(); public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) => Math.Abs(firstValue.Id - secondValue.Id); public static T FromValue<T>(int value) where T : Enumeration => Parse<T, int>(value, "value", item => item.Id == value); public static T FromDisplayName<T>(string displayName) where T : Enumeration => Parse<T, string>(displayName, "display name", item => string.Equals(item.Name, displayName, StringComparison.InvariantCultureIgnoreCase)); private static T Parse<T, TValue>(TValue value, string description, Func<T, bool> predicate) where T : Enumeration => GetAll<T>().FirstOrDefault(predicate) ?? throw new InvalidOperationException($"'{value}' is not a valid {description} in {typeof(T)}"); public int CompareTo(object obj) => Id.CompareTo(((Enumeration)obj).Id); } 该配置适用于持久数据: var cashout = new Cashout { Amount = command.Amount, RecipientAccountId = command.RecipientAccountId, Comment = command.Comment, State = CashoutState.Pending }; dbContext.Cashouts.Add(cashout); dbContext.SaveChanges(); 但是当涉及到基于该状态查询数据时,它惨败,我分别尝试了: 查询给定的特定状态 var cancelledByState = await _dbContext.Cashouts.Where(x => x.State == CashoutState.Cancelled).FirstAsync(); 抛出: System.InvalidOperationException: The LINQ expression 'DbSet<Cashout> .Where(c => c.State.Name == __Cancelled_Name_0)' 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(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information. at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|8_0(ShapedQueryExpression translated, <>c__DisplayClass8_0& ) at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query) at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0() at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler) at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancella tionToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.FirstAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken) 查询给定的特定状态名称 var cancelledByStateName = await _dbContext.Cashouts.Where(x => x.State.Name == CashoutState.Cancelled.Name).FirstAsync(); 抛出: System.InvalidOperationException: The LINQ expression 'DbSet<Cashout> .Where(c => c.State.Name == __Cancelled_Name_0)' 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(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information. at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|8_0(ShapedQueryExpression translated, <>c__DisplayClass8_0& ) at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query) at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0() at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler) at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancella tionToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.FirstAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken) 查询给定的特定状态id var cancelledByStateId = await _dbContext.Cashouts.Where(x => x.State.Id == CashoutState.Cancelled.Id).FirstAsync(); 抛出: System.InvalidOperationException: The LINQ expression 'DbSet<Cashout> .Where(c => c.State.Id == __Cancelled_Id_0)' 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 eith er AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information. at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|8_0(ShapedQueryExpression translated, <>c__DisplayClass8_0& ) at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor) at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query) at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0() at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler) at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancella tionToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.FirstAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken) 我想找到一种使用状态属性来查询 DbSet<Cashout> 的方法。 注 1:在使用内存模式时,它看起来就像一个魅力,但只要上下文绑定到实际的 postgresql 数据库服务器,就会像上面那样失败。 注 2:我还在 GitHub 上创建了 2 个问题: https://github.com/dotnet/efcore/issues/19589 https://github.com/npgsql/efcore.pg/issues/1199 我希望您已经解决了您的问题,但经过几个小时的研究,我发现如何在使用 HasConversion 时修复 LINQ 查询。基本上,您需要使用要转换的对象中带有隐式运算符的原始类型进行强制转换,请参阅这篇文章了解更多详细信息。 现在,如果您需要更复杂的类型,EF Core 8 中具有复杂类型。
如何在 Azure Function 上抑制或静音 EF Core 数据库命令
我有以下 host.json 设置,试图抑制日志和 Application Insights 拾取 EF Core 命令,但它不起作用(命令仍然显示)。 这是host.json { ...
我有多对多关系,但EF Core似乎不识别它。 JobOffer 和 JobOfferTag 之间存在关系。 JobOffer继承自BaseJobOffer: 公共类 BaseJobOff...
我有一个抽象的 AuditObject 类,其中包含我可以在保存实体更改之前自动设置的审核字段。 公共抽象类 AuditObject { 公共字符串创建者{获取;放; }
.Where() 中的 Contains() EF Core 不起作用 .NET Core 3.1.8
我有以下代码不起作用: var bookIds = source.Sids.Split(","); var HKM = _context.Books .include(b => b.Writer) .
如何使用 EF Core 和 SQL 数据库确保文档顺序编号?
我有一个简单的应用程序,必须为创建的每个文档分配一个没有间隙或重复的连续编号,即 1、2、3 等。不同的文档类型将具有不同的编号
Entity Framework Core - 使用 OData 执行 NOLOCK 查询
我正在尝试使用 NOLOCK 执行 EF Core 查询,有一篇文章演示了如何编写扩展方法,但它在 OData 查询中无法按预期工作。 链接在这里: 哈...