C#Entity Framework从嵌套对象返回列表

时间:2016-09-29 13:31:02

标签: c# entity-framework linq

如何使用dbWagonList中的docInclude()返回?

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.Id = 73243;
            document.Name = "SendingForm";
            document.Wagons = new Wagons
            {
                Depos = "Main",
                Id = 1,
                Street = "WestSide",
                WagonList = new List<Wagon> 
            { 
                new Wagon {Code="MP",Destination="China",Id=1,Number=90543 }, 
                new Wagon { Code="MO",Destination="Bangkok",Id=2,Number=90543}, 
                new Wagon {Code="MI",Destination="Burma",Id=3,Number=90543 } 
            }
            };
            using (var db = new SoccerContext())
            {
                //db.documents.Add(document);
                //db.SaveChanges();
                Document doc = db.documents.Include("Wagons").FirstOrDefault();
            }
        }
    }

    public class Document
    {
        [Key]
        public int Id { get; set; }

        public string Name { get; set; }

        public Wagons Wagons { get; set; }
    }

    public class Wagons
    {
        [Key]
        public int Id { get; set; }

        public string Depos { get; set; }

        public string Street { get; set; }

        public List<Wagon> WagonList { get; set; }
    }

    public class Wagon
    {
        [Key]
        public int Id { get; set; }

        public string Code { get; set; }

        public int Number { get; set; }

        public string Destination { get; set; }
    }

    class SoccerContext : DbContext
    {
        public SoccerContext()
            : base("DocumentDB")
        { }

        public DbSet<Document> documents { get; set; }
    }
}

1 个答案:

答案 0 :(得分:2)

对于single Document object,它是直截了当的:

var wagonList = doc.Wagons.WagonList

对于List of Documents执行此操作(将展平文档层次结构中的货车列表):

var wagonList = docList.SelectMany(doc => doc.Wagons.WagonList);