How do I initialize an empty list within an Entity Framework query?

c# entity-framework entity-framework-6

Accepted Answer

Interestingly, even thoughnew string[0] and { } fail to work,new string[] { } and new string[0] { } do!

return MyContext.Foos.ToList()
    .Select(foo=> new Foo
    {
        Id = foo.Id,
        Name = foo.Name,
        RequiredFeatures = new string[] { }
    }).ToList();

This does come with the restriction that you cannot add items to the list since it is supported by an array rather than a real list. I'm not clear why Entity Framework only supports some of them and not the others as they all appear to perform the same.

Unfilled collections

Supported:

  • new string[] { }
  • new string[0] { }

Not encouraged:

  • { }
  • new string[0]
  • new List<string>()
  • new List<string> { }
  • new List<string>() { }

containing no empty spaces

Supported:

  • new [] { "foo" }
  • new string[] { "foo" }
  • new string[1] { "foo" }
  • new List<string> { "foo" }
  • new List<string>() { "foo" }

Not encouraged:

  • { "foo" }

It is intriguing that although an empty list is not supported by Entity Framework, a list containing values is.

8
3/9/2018 2:02:44 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow