【问题标题】:child relationship not available in parent object父对象中不可用的子关系
【发布时间】:2021-01-22 14:29:20
【问题描述】:

我有以下返回工厂汽车列表的方法。

可以,但是顺序不对。

CarEngines 可以有一个 orderId,我想通过它来订购。

查看此处的其他答案,我发现您无法在查询中下订单,您必须事后进行。

问题是,我无法访问CarEngines,如下所示:

public async Task<ActionResult<CountryList>> GetCountryCarObject(Guid countryID)
{
    var factoryCars = await _context.CountryList
        .Include(n => n.CarList).ThenInclude(l => l.CarEngines)
        .Include(n => n.CarList).ThenInclude(l => l.CarOptions)
        .SingleOrDefaultAsync(c => c.CountryId == countryID);

    factoryCars.CarList.CarEngines  <== CarEngines doesn't show up in CarList object

    return factoryCars;
}

它告诉我 CarList 不包含 CarEngines 的定义。

但它在我的 CarList 模型中,我将其定义如下:

public CarList()
{
    CarEngines = new HashSet<CarEngines>();
}

public virtual ICollection<CarEngines> CarEngines { get; set; }

这是两个模型:

public partial class CarList
{
    public CarList()
    {
        CarEngines = new HashSet<CarEngines>();
        CarOptions = new HashSet<CarOptions>();
    }

    public string CarId { get; set; }
    public string CarMake { get; set; }
    public string CarModel { get; set; }
    public Guid? CarCountryId { get; set; }

    public virtual ICollection<CarEngines> CarEngines { get; set; }
    public ICollection<CarOptions> CarOptions { get; set; }
}


public partial class CountryList
{
    public CountryList()
    {
        CarList = new HashSet<CarList>();
    }

    [Key]
    public Guid CountryId { get; set; }
    public string CountryName { get; set; }
    public string CountryLocation { get; set; }
    public string CountryDesc { get; set; }

    public virtual ICollection<CarList> CarList { get; set; }

}

所以我不确定它没有看到它。

有没有办法让它工作?

谢谢!

【问题讨论】:

  • 您是否收到错误消息?如果是这样,那是什么错误?或者这是 Intellisense 的问题?
  • 给我们所有类的代码。 CountryList, CarList 应该足够了
  • @NolanBradshaw 我收到了CarList doesn't contain a definition for CarEngines
  • @NolanBradshaw Visual Studio 中的完整错误是:Error CS1061 'ICollection&lt;CarList&gt;' does not contain a definition for 'CarEngines' and no accessible extension method 'CarEngines' accepting a first argument of type 'ICollection&lt;CarList&gt;' could be found
  • @A_kat 谢谢!我添加了那些

标签: asp.net-core entity-framework-core asp.net-core-3.1


【解决方案1】:

好吧,事实上有一个叫做CarList但不是一个列表的东西是非常令人困惑的,但继续前进....

问题在于CarList 是一个列表。所以使用factoryCars.CarList.Select( x=&gt;x.CarEngines)之类的东西。还要将其重命名为 var country 而不是 var factoryCars,因为您返回的是一个国家而不是汽车列表。

同时重命名你的变量和类,这种混乱可能是由这个引起的。例如,您可以将其重命名为 ICollection&lt;Car&gt; Cars 而不是 ICollection&lt;CarList&gt; CarList,所以现在从名称中您可以轻松理解有多个汽车(因此它是一个集合),其中包括对象 Car

【讨论】:

  • 谢谢,我会试一试,你看到的一些代码是我创建项目并运行 .net core 数据库脚手架命令时 .NetCore EF 自动生成的。就像 HashSet 一样。 :)
  • 我应该使用factoryCars.CarList.Select( x=&gt;x.CarEngines) 代替ThenInclude 行还是将其放在它下面?谢谢!
  • 此外,您可以使用Table 属性来安全地重命名类
  • 谢谢!所以我补充说......它会自动订购还是我需要创建另一个对象来订购?
猜你喜欢
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多