我有很多不同的代碼級別表(1 到 5,取決于表代表的區域)。您可以使用它們以不同的粒度級別進行搜索。所以我做了一個較小的例子。EF 中的表位于下方并添加到背景關系 dbcontext。
public interface IDim1
{
int Id { get; set; }
string Dim1Code { get; set; }
}
public class Dim1 : IDim1
{
public int Id { get; set; }
public string Dim1Code { get; set; }
}
public interface IDim2 : IDim1
{
string Dim2Code { get; set; }
}
public class Dim2 : IDim2
{
public string Dim2Code { get; set; }
}
public interface IDim3 : IDim2
{
string Dim3Code { get; set; }
}
public class Dim3 : Dim2, IDim3
{
public string Dim3Code { get; set; }
}
public class House : Dim2
{
public string House { get; set; }
}
public class Car : Dim1
{
public string Car { get; set; }
}
public class Work : Dim3
{
public string Employeer { get; set; }
}
public bool DimensionCodeExists<T>(string code) where T : Dim1
{
var Querable = dbcontext.Set<T>().AsQuerable();
if (typeof(Dim3).IsAssignableFrom(typeof(T)))
{
// They trouble is here
return Querable.Cast<Dim3>().Any(o => o.Dim3Code == code || o.Dim2Code == code || o.Dim1Code == code);
}
else if (typeof(Dim2).IsAssignableFrom(typeof(T)))
{
// also here
return Querable.Cast<Dim2>().Any(o => o.Dim2Code == code || o.Dim1Code == code);
}
else
{
// also here
return Querable.Cast<Dim1>().Any(o => o.Dim1Code == code);
}
}
他們的麻煩就在這里,我真的需要告訴它有要搜索的那些代碼,但我不能將它轉換為 Dim3(或 Dim2 或 Dim1),因為那時 EF 將使用運算式進行回應......“LINQ to Entities 僅支持轉換物體資料模型原始型別”我如何轉換它以便我可以搜索我現在知道 T 具有的三個引數。
uj5u.com熱心網友回復:
嘗試使用反射:
private bool Dim3CodeExists<T>(string code) where T : Dim3
{
return dbcontext.Set<T>().Any(o => o.Dim3Code == code || o.Dim2Code == code || o.Dim1Code == code);
}
private bool Dim2CodeExists<T>(string code) where T : Dim2
{
return dbcontext.Set<T>().Any(o => o.Dim2Code == code || o.Dim1Code == code);
}
private bool Dim1CodeExists<T>(string code) where T : Dim1
{
return dbcontext.Set<T>().Any(o => o.Dim1Code == code);
}
public bool DimensionCodeExists<T>(string code) where T : Dim1
{
if (typeof(Dim3).IsAssignableFrom(typeof(T)))
{
var openMethod = typeof(YourClass).GetMethod(nameof(Dim3CodeExists), BindingFlags.NonPublic | BindingFlags.Instance);
var boundMethod = openMethod.MakeGenericMethod(typeof(T));
return (bool)boundMethod.Invoke(this, new[] { code });
}
if (typeof(Dim2).IsAssignableFrom(typeof(T)))
{
var openMethod = typeof(YourClass).GetMethod(nameof(Dim2CodeExists), BindingFlags.NonPublic | BindingFlags.Instance);
var boundMethod = openMethod.MakeGenericMethod(typeof(T));
return (bool)boundMethod.Invoke(this, new[] { code });
}
return Dim1CodeExists<T>(code);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311168.html
