1

How to return from db, WagonList in doc using Include()?

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
  • 1
    What's not working exactly? Document doc = db.documents.Include(x => x.WagonList).FirstOrDefault(); should work. And even if you didn't use Include, EF would lazy load the wagons when you access the WagonList property. Commented Sep 29, 2016 at 13:34

1 Answer 1

2

For a single Document object, its straight forward:

var wagonList = doc.Wagons.WagonList

For a List of Documents do this (will flatten the List of wagons inside the document hierarchy):

var wagonList = docList.SelectMany(doc => doc.Wagons.WagonList);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.