I came across this exception in the past after upgrading .NET Core 2.2 to 3.0. I didn’t write about it before but recently I saw this exception again in our error logs so I thought I’d write about this and how to solve it.
If you have a model like this
public class Book
{
public Guid Id { get; set; }
public string Name { get; set; }
public IEnumerable<Author> Authors { get; set; } = Enumerable.Empty<Author>();
}
public class Author
{
public Guid Id { get; set; }
public string Name { get; set; }
}
That Enumerable.Empty<Author>() is to set the property Authors to be empty instead of null by default. When you deserialise a JSON string to model Book, if there are authors in the JSON string, then it’s fine. However, if there are no authors in the JSON string, then it would throw this exception
Cannot create and populate list type System.Linq.EmptyPartition`1[SampleProject.Models.Book]
To fix this problem, you could simply remove the Enumerable.Empty<Author>(). However this means the default value for Authors would be null. Alternatively, if you want to keep the default to be empty collection of authors, you can replace Enumerable.Empty<Author>() with new List<Author>().
public class Book
{
public Guid Id { get; set; }
public string Name { get; set; }
public IEnumerable<Author> Authors { get; set; } = new List<Author>();
}
public class Author
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Now if you try with these JSON strings, it should work.
{
"Id": "81807e69-6ae6-4a5a-8ac4-9c58734b5604",
"Name": "Sample book"
}
{
"Id": "81807e69-6ae6-4a5a-8ac4-9c58734b5604",
"Name": "Sample book",
"Authors": []
}