gpt4 book ai didi

c# - EF - 无法将运算符 '==' 应用于类型为 'TId' 和 'TId' 的操作数

转载 作者:可可西里 更新时间:2023-11-01 08:24:21 27 4
gpt4 key购买 nike

我有这个通用类,它使用 Entity Framework 6.x。

public class GenericRepository<TEntity, TId> where TEntity, class, IIdentifyable<TId>
{
public virtual TEntity GetById(TId id)
{
using (var context = new DbContext())
{
var dbSet = context.Set<TEntity>();
var currentItem = dbSet.FirstOrDefault(x => x.Id == id);
return currentItem;
}
}

public virtual bool Exists(TId id)
{
using (var context = new DbContext())
{
var dbSet = context.Set<TEntity>();
var exists = dbSet.Any(x => x.Id == id);
return exists ;
}
}
}

还有这些接口(interface):

public interface IIdentifyable : IIdentifyable<int>
{
}

public interface IIdentifyable<out TId>
{
TId Id { get; }
}

实体看起来像这样:

public class CustomerEntity : IIdentifyable<int>
{
public string Name { get; set; }
public int Id { get;set; }
}

public class ProductEntity : IIdentifyable<Guid>
{
public string Name { get; set; }
public Guid Id { get;set; }
}

我的问题是它无法编译。我收到此错误:

Cannot apply operator '==' to operands of type 'TId' and 'TId'

我试图将其更改为 x => Equals(x.Id, id),但 EF 无法翻译它。有什么办法吗?

我知道我可以使用 Find() 而不是 FirstOrDefault。但是我需要的不仅仅是上面提到的方法。 有什么方法可以让 EF 将 TIdTId 进行比较? TId 目前只有 guidint。我已经看到下面的问题,但它们没有处理有关转换为 SQL 的问题。

Can't operator == be applied to generic types in C#?

How to solve Operator '!=' cannot be applied to operands of type 'T' and 'T'

最佳答案

更新:这是一种与 EF 一起使用的简单简洁的方法。

将以下约束添加到 GenericRepository

where TId : IEquatable<TId>

然后使用 Equals方法

x => x.Id.Equals(id);

原答案:

这是泛型的一个已知问题,通常使用 EqualityComparer<T>.Default 处理。而不是 ==运算符(operator)。但是,这种方法不适用于 LINQ to Entities。

解决它的一种方法是使用 Expression 动态构建谓词来自 System.Linq.Expressions 的类(class)像这样的命名空间:

public class GenericRepository<TEntity, TId> where TEntity: class, IIdentifyable<TId>
{
protected static Expression<Func<TEntity, bool>> EqualsPredicate(TId id)
{
Expression<Func<TEntity, TId>> selector = x => x.Id;
Expression<Func<TId>> closure = () => id;
return Expression.Lambda<Func<TEntity, bool>>(
Expression.Equal(selector.Body, closure.Body),
selector.Parameters);
}
}

并像这样使用它:

dbSet.FirstOrDefault(EqualsPredicate(id));

dbSet.Any(EqualsPredicate(id));

等等

关于c# - EF - 无法将运算符 '==' 应用于类型为 'TId' 和 'TId' 的操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40132380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com