C#6介绍了如何初始化对象和集合的一些很好的补充。
例如,此代码在C#6中有效:
void Main()
{
var ints = new[] { 1, 2, 3, 4, 5 };
var myClass = new MyClass
{
// IEnumerableExtensions.Add<T> is called.
Items = { ints }
};
Console.WriteLine(myClass.Items.Count());
}
class MyClass
{
public ICollection<int> Items { get;} = new List<int>();
}
public static class IEnumerableExtensions
{
public static void Add<T>(this ICollection<T> collection, IEnumerable<T> items)
{
var list = collection as List<T>;
if (list != null)
{
list.AddRange(items);
return;
}
foreach (var item in items)
{
collection.Add(item);
}
}
}
所以现在可以为具有只读集合属性的对象编写初始化表达式。
有时我需要告诉EF如何组装实体:
from name in names
join addr in infoSecEmailAddresses
on name.LegalEntityIsn equals addr.LegalEntityIsn into addresses
where legalEntityIsns.Contains(name.LegalEntityIsn)
select new LegalEntitySideInfoSecParameters
{
LegalEntityIsn = name.LegalEntityIsn,
LegalEntityName = name.FullNameNominative,
Emails = addresses.Select(
a => new Email
{
EmailAddress = a.Address,
RecipientPriority = a.RecipientPriority
}).ToList()
}
这里Emails
属性需要是可写的。但是使用上面的代码,可以将其设置为只读并重写代码,如下所示:
Emails = {
addresses.Select(
a => new Email
{
EmailAddress = a.Address,
RecipientPriority = a.RecipientPriority
})
}
实际上,可以通过将稍后在客户端(AsEnumerable()
)上转换的匿名类型的DTO引入所需实体来完成此操作。尽管如此,我希望EF7能够支持该功能。