C# 6 introduced some cool additions to how objects and collections are initialized.
For example this code is valid in 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);
}
}
}
So now it's possible to write initialization expression for the objects with read-only collection properties.
And sometimes I need to tell EF how assemble the entity:
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()
}
Here Emails
property need to be writable. But with the upper code it would be possible to make it read-only and rewrite code like this:
Emails = {
addresses.Select(
a => new Email
{
EmailAddress = a.Address,
RecipientPriority = a.RecipientPriority
})
}
Actually, this can be done by introducing DTO with anonymous type later converted on the client (AsEnumerable()
) to the required entity. Nonetheless, I'd like to have that feature supported by EF7 itself.