【问题标题】:Why does Stack<T> not work as a navigation propery in EF为什么 Stack<T> 不能在 EF 中用作导航属性
【发布时间】:2015-12-02 14:59:02
【问题描述】:

我偶然发现了这个;我将导航属性定义为 Stack;虽然当我尝试使用Include 查询实体时,DB 关系创建得很好,但它说A specified Include path is not valid. The EntityType 'BreakAway.Destination' does not declare a navigation property with the name 'Lodgings'. 根据这个post 的公认答案,只要导航属性类型实现ICollection 应该没问题。我只是仔细检查Stack&lt;T&gt; 确实实现了ICollection

实体是:

 public class Destination
    {
        public Destination()
        {
            Lodgings = new Stack<Lodging>();
        }

        public string Name { get; set; }
        public string Country { get; set; }
        public int DestinationId { get; set; }
        public string Description { get; set; }
        public byte[] Photos { get; set; }
        public virtual Stack<Lodging> Lodgings { get; set; }
    }

  public sealed class Lodging
    {
        public int LodgingId { get; set; }
        public string Name { get; set; }
        public string Owner { get; set; }
        public bool IsResort { get; set; }
        public decimal MilesFromNearestAirport { get; set; }
        public Destination Destination { get; set; }
        public int DestinationId { get; set; }
    }

简单的测试查询:

        private static void QueryDestination()
        {
            using (var context = new Context())
            {
                var dest = context.Destinations.Include(d => d.Lodgings).First();
                Console.WriteLine("Destination Name: {0}",dest.Name);
                Console.WriteLine("Lodging Name " + dest.Lodgings.First().Name);

            }
        }

【问题讨论】:

  • 您是否尝试将定义更改为ICollection 像这样public virtual ICollection&lt;Lodging&gt; Lodgings
  • Stack&lt;T&gt; 没有实现ICollection&lt;T&gt;
  • @YacoubMassad 所说的,Stack&lt;T&gt; 实现了ICollection,而不是ICollection&lt;T&gt;
  • 即使它起作用了也毫无意义,因为数据库行是无序的。

标签: c# entity-framework ef-code-first navigation-properties


【解决方案1】:

导航属性必须是实现ICollection&lt;T&gt; 而不是ICollection 的类型。 Stack&lt;T&gt; 只实现了ICollection

引用this reference:

表示关系“多”端的导航属性必须返回实现 ICollection 的类型,其中 T 是关系另一端的对象类型。

参考中的 ICollection 有一个链接指向 ICollection&lt;T&gt; 的 MSDN 参考。

【讨论】:

  • 你能提供一个参考吗?
  • 好的,谢谢。不知道他们为什么不直接在文章中使用 ICollection ,这会使这更清楚一些。感谢您的回答。
猜你喜欢
  • 2015-05-30
  • 1970-01-01
  • 2014-11-01
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 2021-08-13
相关资源
最近更新 更多