gpt4 book ai didi

c# - 一种通用的 Find 方法,用于按 Guid 类型搜索实现 IDbSet 接口(interface)的类

转载 作者:行者123 更新时间:2023-11-30 22:24:25 26 4
gpt4 key购买 nike

我正在通过实现 IDbSet 接口(interface)来实现 FakeDataSet 类。作为实现此接口(interface)的一部分,我必须实现 Find 方法。我所有的实体类都有一个 Guid 类型的 Id 列。我正在尝试为此 FakeDbSet 类实现 Find 方法,但很难以通用方式编写它。以下是我编写此方法的尝试。

public class FakeDataSet<T> : IDbSet<T> where T: class, new()  
{
// Other methods for implementing IDbSet interface
public T Find(params object[] keyValues)
{
var keyValue = (Guid)keyValues.FirstOrDefault();
return this.SingleOrDefault(m => m.Id == keyValue); // How can I write this
}
}

因为它不知道 Id 是 Guid 类型,所以我在调用 m.Id 时遇到编译错误。

'T' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

关于如何实现这一点有什么想法吗?

最佳答案

像这样给你一个想法:

public virtual T Find(params object[] keyValues)
{
if (keyValues.Length != _keyProperties.Count)
throw new ArgumentException("Incorrect number of keys passed to find method");

IQueryable<T> keyQuery = this.AsQueryable<T>();

for (int i = 0; i < keyValues.Length; i++)
{
var x = i; // nested linq

keyQuery = keyQuery.
Where(entity => _keyProperties[x].GetValue(entity, null).Equals(keyValues[x]));
}

return keyQuery.SingleOrDefault();
}

来源:Generic Repository: Fake IDbSet implementation update (Find Method & Identity key)

关于c# - 一种通用的 Find 方法,用于按 Guid 类型搜索实现 IDbSet 接口(interface)的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774979/

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