[英]Entity Framework (5.0) Code First - Insert into Collection within Collection
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. 我目前正在寻找将记录插入Workshop Times的最佳方法,这是首先使用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; }
}
You are definitely on the right track with your query, however your include statements appear incorrect. 您的查询肯定走在正确的轨道上,但是您的include语句似乎不正确。 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) 另外,您可以使用lambda来执行相同的操作(但要确保其类型安全)
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 EF代码优先-Include(x => x.Properties.Entity)a 1:多关联
or from rowan miller (from EF team) 或来自Rowan Miller(来自EF团队)
http://romiller.com/2010/07/14/ef-ctp4-tips-tricks-include-with-lambda/ 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? ) 并确保您using System.Data.Entities
基于lambda的include的using System.Data.Entities
( DbQuery.Include()的重载在哪里花费了lambda? )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.