Elvin Mammadov
Elvin Mammadov

Reputation: 27387

Custom function for Include method in EF

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.

Upvotes: 0

Views: 1908

Answers (1)

Igor
Igor

Reputation: 62213

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<>.

Upvotes: 2

Related Questions