为什么Stack <t>不能用作EF中的导航属性

时间:2015-12-02 14:59:02

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

我偶然发现了这个;我将导航属性定义为Stack;虽然当我尝试使用Include查询实体时,数据库关系已正常创建,但它显示A specified Include path is not valid. The EntityType 'BreakAway.Destination' does not declare a navigation property with the name 'Lodgings'. 根据此post的接受答案,只要导航属性类型实现ICollection,它应该没问题。我只是仔细检查Stack<T>是否实现了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);

            }
        }

1 个答案:

答案 0 :(得分:2)

导航属性必须是实现ICollection<T>而不是ICollection的类型。 Stack<T>仅实施ICollection

引自this reference

  

一个导航属性,代表&#34;很多&#34;关系的结尾必须返回一个实现 ICollection的类型,其中T 是关系另一端的对象类型。

引用中的ICollection有一个指向ICollection<T>的MSDN参考的链接。