我有以下问题 - 有限的 ORM 强加了基础设施与域对象的耦合。
请注意,这是一个 Windows 应用商店应用程序,并且 Reflection API 与标准 .Net 不同
例如,我必须像这样手动实现导航属性(代码中的关系)(假设我有一本包含一对多子章节集合的书聚合):
List<Chapters> Chapters
{get {return db.Query<Chapters>.Where(b => b.BookId == this.Id);}}
我想通过通用扩展方法来减少这种耦合,该方法将为父实体检索子实体,例如
IEnumerable<T> GetChildren<TParent,TChild>(this TParent parent)
where TParent, TChild : Entity
我可以假设所有实体都有一个 Id 主键属性,外键由父实体名称和 Id(“BookId”)组成
假设 this 参数是父实体,如何在此扩展方法中实现 db.Query.Where Linq 方法的谓词?
最佳答案
像这样(简化版本):
public static TChild GetHierarchyChild<TParent, TChild>(this TParent parent)
{
var pType = typeof(TParent);
var chType = typeof(TChild);
var chPropInfo = pType
.GetProperties()
.FirstOrDefault(p => p.PropertyType == chType);
if (chPropInfo == null)
{
return default(TChild);
}
return (TChild)chPropInfo.GetValue(parent);
}
public class A
{
public IEnumerable<B> Bs
{
get
{
return new[] { new B(1) };
}
}
}
public class B
{
public B(int id)
{
Id = id;
}
public int Id { get; protected set; }
}
示例:
var a = new A();
var bs = GetHierarchyChild<A, IEnumerable<B>>(a);
bs.ToString();
关于c# - 为 Linq (2Sqlite) 编写谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19116744/