我使用EF Core 1創建ASP.NET Core 1應用程序。我有兩個類具有一對多關係,如下所示

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

在此之後我得到了這個錯誤

實體類型“Country”上的導航屬性“Singers”的類型是“IQueryable”,無法創建具體實例。在使用之前初始化屬性,向該類型添加公共無參數構造函數,或使用可以分配HashSet <>或List <>的類型。

我對解決方案一無所知。請幫忙。

一般承認的答案

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

應該

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

異常消息幾乎準確地說明了什麼是錯誤的以及應該改變什麼。您幾乎可以使用任何派生自HashSet<>List<>



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow