EF中包含方法的自定义函数

Custom function for Include method in EF

我使用 EF Core 1 创建 ASP.NET Core 1 应用程序。我有两个 class 具有如下一对多关系

 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; }
 }

以及他们的映射

 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);
    }
 }

我为此实体创建了通用存储库模式。有一个包含 属性 的函数如下

  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();
    }

我调用这个方法

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

然后我得到这个错误

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

我不知道解决办法。 请帮忙。

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

应该是

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

异常消息几乎准确地说明了错误所在以及应该更改为什么。您几乎可以使用派生自 HashSet<>List<>.

的任何类型