このサンプルクラス構造を考慮に入れる-
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; }
}
上記のドキュメントと提供されたサンプルクラス構造に基づいて、実行時に不明なランダムプロパティを選択するための動的セレクターをコンパイルするのに苦労してきました。私が抱えている主な問題は、返されたApprenticeにリンクされているすべてのアドレスの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();
私が抱えている問題は、ネストされたコレクションから特定のプロパティ(実行時には不明)を取得する構文を決定することです
これは、 System.Linq.Dynamic.Coreを使用して簡単に実行できます。
var data = new[]
{
new Apprentice { FamilyName = "f", Addresses = new [] { new ApprenticeAddress { AddressLine1 = "address x" }, new ApprenticeAddress { AddressLine1 = "address y" } } }
}.AsQueryable();
var result = data.Select(x => new { x.FamilyName, Addresses = x.Addresses.Select(y => y.AddressLine1) });
Console.WriteLine("result: " + JsonConvert.SerializeObject(result, Formatting.Indented));
var resultDynamic = data.Select("new (FamilyName as FamilyName, Addresses.Select(AddressLine1) as Addresses)");
Console.WriteLine("resultDynamic: " + JsonConvert.SerializeObject(resultDynamic, Formatting.Indented));
完全に機能する例については、 https: ConsoleApp2
を参照してください。
Addresses.SelectMany(y => y.AddressLine1)
が間違っていることに注意してください。これにより、アドレスから文字が選択されます。