gpt4 book ai didi

c# - 实体的通用键

转载 作者:太空狗 更新时间:2023-10-30 01:15:37 25 4
gpt4 key购买 nike

我在这两个错误之间徘徊,试图通用化大约 50 个类共享的一些实体代码。

Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.

Operator '==' cannot be applied to operands of type 'TKey' and 'TKey'

public abstract class BaseRepository<TEntity, TKey> : BaseRepository
where TEntity : KeyedBaseModel<TEntity, TKey>
{
public BaseRepository(MyProjectContext context)
{
Context = context;
}

protected MyProjectContext Context { get; set; }

public async Task<TEntity> SelectById(TKey id)
{
return await Context.Set<TEntity>().FirstOrDefaultAsync(s => s.Id == id);
}
}

这里存在问题:

s => s.Id == id

如果我使用 == 对于使用 Guid 作为主键的对象,我会得到一个错误,如果我使用...

s => s.Id.Equals(id)

我收到一条错误消息,指出 Entity 无法创建 System.Object 类型的常量值。

最佳答案

我猜你会想要类似的东西

public class KeyedBaseModel<TEntity, TKey>
{
public static readonly Type EntityType = typeof(TEntity);
public static readonly Type KeyType = typeof(TKey);
public static readonly PropertyInfo KeyProperty = EntityType.GetProperty(nameof(Id), BindingFlags.Public | BindingFlags.Instance);

public static Expression<Func<TEntity, bool>> IdEquals(TKey key)
{
var parameter = Expression.Parameter(EntityType, "x"); // x =>
var property = Expression.Property(parameter, KeyProperty); // x => x.Id
var constant = Expression.Constant(key, KeyType); // id
var equal = Expression.Equal(property, constant); // x => x.Id == id

return Expression.Lambda<Func<TEntity, bool>>(equal, parameter);
}

public TKey Id { get; protected set; }
}

像这样在你的仓库中使用

    public async Task<TEntity> SelectById(TKey id)
{
var idEquals = KeyedBaseModel<TEntity, TKey>.IdEquals(id);
return await Context.Set<TEntity>().FirstOrDefaultAsync(idEquals);
}

根据我的测试,这是可行的,但我不喜欢这种设计(当然你可能有一些合理的理由)

我会坚持使用 Guid 作为键并将 KeyedBaseModel 转换为单个参数通用类型甚至非通用基本实体类型。

编辑我刚刚在 Entitty Framework Core (RC 2) 中尝试过,它有效

public async Task<TEntity> SelectById(TKey id)
{
return await Context.Set<TEntity>().FirstOrDefaultAsync(s => s.Id.Equals(id));
}

关于c# - 实体的通用键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37473037/

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