0

I've got three classes.

Event > Workshop > Workshop Times

I'm currently looking for best way of inserting records into the Workshop Times, this is running through code first using ICollections.

Looking for something along the lines of this, but I know it doesn't work:

       //Create connection
        var db = new Context();

        var Event = db.Events
            .Include("Workshops")
            .Include("Workshops.Times")
            .Where(ev => ev.GUID == EventGUID).FirstOrDefault();

        Event.Workshops.Add(new Workshop
        {
            Name = tbWorkshopName.Text,
            Description = tbWorkshopDescription.Text,
            Times.Add(new WorkshopTime{
                //Information for times
            })
        });

        db.SaveChanges();

Chopped down classes:

public class Workshops{
    public int id { get; set; }
    public string name { get; set; }
    public ICollection<WorkshopTimes> Times{get;set;}
}
public class Events {
    public int id { get; set; }
    public string name { get; set; }
    public ICollection<Workshops> WorkShops { get; set; }
}

public class WorkshopTimes {
    public int id { get; set; }
    public DateTime time { get; set; }
}
ItWontWork
  • 67
  • 1
  • 5

1 Answers1

0

You are definitely on the right track with your query, however your include statements appear incorrect. From your model I would expect:

    var Event = db.Events
        .Include("WorkShops")
        .Include("WorkShops.events")
        .Where(ev => ev.GUID == EventGUID).FirstOrDefault();

Note this uses the property names not the types. This will ensure that the entities in the listed nav properties will be included in the result.

In addition you can use a lambda to do the same thing (but its typesafe)

Check out here for how to do a very similar scenario to yours:

EF Code First - Include(x => x.Properties.Entity) a 1 : Many association

or from rowan miller (from EF team)

http://romiller.com/2010/07/14/ef-ctp4-tips-tricks-include-with-lambda/

And make sure you are using System.Data.Entities for lambda based includes ( Where did the overload of DbQuery.Include() go that takes a lambda? )

Community
  • 1
  • 1
undefined
  • 33,537
  • 22
  • 129
  • 198
  • I'd typed the classes manually to be honest, the original query is correct for the actual classes in the project. Wasn't on my computer to get the actual classes from the project. -- I'm able to query the results and get what I need back, it's the insert that I'm having issues with. Cheers. – ItWontWork Nov 21 '12 at 10:48
  • @ItWontWork Could you add in some more detail about what isnt working, what behavior are you seeing – undefined Nov 21 '12 at 18:54