我发布了这个,所以可能需要它的人可以使用它。也许这可以通过某种方式得到改善。(受 Breeze DocCode 启发(感谢 Northwind 控制器中的 Partial Class Api 方法 :))
可以通过以下方式查询不同的值:为了能够使用 Distinct(IEqualityComparer) 方法,查询必须在内存中作为 IEnumerable。EqualityComparer 不能转换为 SQL 语句。因此应用 where 子句,然后由比较器过滤结果记录。
return query.AsQueryable()
: 为了能够使用 skip/take 和 inlineCount,查询必须是IQueryable<T>
. 为此方法AsQueryable()
。
//The API Method ----------
[HttpGet]
public IQueryable<MvlOPPersonPartial> MvlOpsPerson(long mvlId)
{
var query = (from op in ContextProvider.Context.MvlOps
where op.MvlId == mvlId
select new MvlOPPersonPartial()
{
MvlId = op.MvlId,
Kundenname = op.Kundenname,
Kundennummer = op.Kundennummer,
Id_P = op.Id_P
})
.AsEnumerable()
.Distinct(new PropertyComparer<MvlOPPersonPartial>("Id_P"));
return query.AsQueryable();
}
public class MvlOp
{
...
public string Kostenstelle { get; set; }
public string Betreuer_Id { get; set; }
public decimal? Id_P { get; set; }
public string Kundenname { get; set; }
public string Kundennummer { get; set; }
public string Person_Typ1 { get; set; }
...
}
//The partial class needed for distinct values ------------
//MvlOP cannot be constructed in an LINQ to Entities query
public class MvlOPPersonPartial
{
public long MvlId { get; set; }
public string Kundenname { get; set; }
public string Kundennummer { get; set; }
public decimal? Id_P { get; set; }
}
//A generic comparer ---------------
public class PropertyComparer<T> : IEqualityComparer<T>
{
private PropertyInfo _PropertyInfo;
/// <summary>
/// Creates a new instance of PropertyComparer.
/// </summary>
/// <param name="propertyName">The name of the property on type T
/// to perform the comparison on.</param>
public PropertyComparer(string propertyName)
{
//store a reference to the property info object for use during the comparison
_PropertyInfo = typeof(T).GetProperty(propertyName,
BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
if (_PropertyInfo == null)
{
throw new ArgumentException(string.Format("{0} is not a property of type {1}.", propertyName, typeof(T)));
}
}
#region IEqualityComparer<T> Members
public bool Equals(T x, T y)
{
//get the current value of the comparison property of x and of y
object xValue = _PropertyInfo.GetValue(x, null);
object yValue = _PropertyInfo.GetValue(y, null);
//if the xValue is null then we consider them equal if and only if yValue is null
if (xValue == null)
return yValue == null;
//use the default comparer for whatever type the comparison property is.
return xValue.Equals(yValue);
}
public int GetHashCode(T obj)
{
//get the value of the comparison property out of obj
object propertyValue = _PropertyInfo.GetValue(obj, null);
if (propertyValue == null)
return 0;
else
return propertyValue.GetHashCode();
}
#endregion
}