【发布时间】:2018-10-21 16:53:25
【问题描述】:
考虑到这个示例类结构 -
public class Apprentice
{
public Guid Id { get; set; }
public string GivenName { get; set; }
public string FamilyName { get; set; }
public virtual ICollection<ApprenticeAddress> Addresses { get; set; }
}
public class ApprenticeAddress
{
public Guid Id { get; set; }
public Guid ApprenticeId { get; set; }
public virtual Apprentice Apprentice { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Town { get; set; }
public Guid CountyId { get; set; }
public virtual County County { get; set; }
public string PostCode { get; set; }
public bool IsPrimaryAddress { get; set; }
public Guid AddressTypeId { get; set; }
public virtual AddressType AddressType { get; set; }
}
根据上述文档和提供的示例类结构,我一直在努力编译一个动态选择器,用于选择运行时未知的随机属性。我遇到的主要问题是选择链接到返回的学徒的任何地址的 AddressLine1 属性。
这个示例 LINQ select 将执行我需要做的事情,但任何人都可以帮助将其转换为数据对象初始化字符串吗?
var r = repo.GetAll().ToList().Select(x =>
new
{
x.FamilyName,
addresses = x.Addresses.SelectMany(y => y.AddressLine1)
});
更新
如果我使用以下代码和传递给 Select 扩展方法的数据对象初始化字符串,我会得到我想要的匿名对象 -
var whereTxt = "Active";
var selectTxt = "new (GivenName AS GivenName,FamilyName AS FamilyName)";
var repo = Storage.DataContext.GetRepository<Apprentice>();
return repo.GetAll().Where(whereTxt).Select(selectTxt).AsQueryable();
我遇到的问题是确定从嵌套集合中检索特定属性(在运行时未知)的语法
【问题讨论】:
-
你能举个例子,在“数据对象初始化字符串”下你到底理解了什么?如果你得到了你想要的匿名对象,问题到底出在哪里?
-
我遇到的问题是我希望选择的属性在运行时是未知的,我必须通过字符串选择器创建选择语句。我无法弄清楚在嵌套集合上选择属性的语法。我已经更新了这个问题,以展示我的意思的一个例子。
标签: c# linq dynamic-linq