Custom function for Include method in EF

asp.net-core c# entity-framework entity-framework-core repository-pattern

Question

I create ASP.NET Core 1 application with EF Core 1. I have two class which has one-to-many relationship as follow

 public class Country: EntityBase
 {
    public string Name { get; set; }

    // fields for relations

    public IQueryable<Singer> Singers { get; set; }
 }

 public class Singer : EntityBase
 {
    public string Name { get; set; }

    // fields for relation

    public int CountryId { get; set; }
    public virtual Country Country { get; set; }
 }

And their mapping

 public class SingerMap
 {
    public SingerMap(EntityTypeBuilder<Singer> entityBuilder)
    {
        entityBuilder.HasKey(x => x.Id);
        entityBuilder.Property(x => x.Id).ValueGeneratedOnAdd();

        entityBuilder.Property(x => x.Name).HasMaxLength(500);

        //relational fields
        entityBuilder.HasOne(x => x.Country).WithMany(x => x.Singers).HasForeignKey(x => x.CountryId);
    }
 }

 public class CountryMap
 {
    public CountryMap(EntityTypeBuilder<Country> entityBuilder)
    {
        entityBuilder.HasKey(x => x.Id);
        entityBuilder.Property(x => x.Id).ValueGeneratedOnAdd();
        entityBuilder.Property(x => x.Name).HasMaxLength(500);
    }
 }

I create generic Repository pattern for this entities. There is a function for include property as follow

  public virtual IEnumerable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = _context.Set<T>();
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query.AsEnumerable();
    }

And I call this method

    [HttpGet]
    public JsonResult GetAllForIndex()
    {
        var result = Service.AllIncluding(x => x.Country);
        return Json(result);
    }

And after this I get this error

The type of navigation property 'Singers' on the entity type 'Country' is 'IQueryable' for which it was not possible to create a concrete instance. Either initialize the property before use, add a public parameterless constructor to the type, or use a type which can be assigned a HashSet<> or List<>.

I have not any idea for solution. Please help.

1
0
12/20/2016 12:20:09 PM

Accepted Answer

public IQueryable<Singer> Singers { get; set; }

Should be

public List<Singer> Singers { get; set; }

The Exception message pretty much states exactly what is wrong and what it should be changed to. You can use almost any type that derives from either HashSet<> or List<>.

2
12/20/2016 12:21:00 PM


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