我觉得我的映射应该正确设置,但是当我从db上下文中检索一个项目时,它没有提供任何"映射"与之相关的项目。
我想要的映射是:
顶级项目是"事件"。
一个事件有很多" TimeSlot"与之相关。
TimeSlot有许多与之关联的字符串。
public class MyEvent
{
private ICollection<TimeSlot> mTimeSlots;
public virtual ICollection<TimeSlot> TimeSlots
{
get{return mTimeSlots ?? (mTimeSlots = new Collection<TimeSlot>());}
set{mTimeSlots = value;}
}
[Key]
public int Id {get;set;}
}
我的TimeSlot看起来像:
public class TimeSlot
{
private ICollection<string> mItems;
public virtual ICollection<string> Items
{
get { return mItems ?? (mItems = new Collection<string>()); }
set { mItems = value; }
}
[Key]
public virtual int Id { get; set; }
public virtual string Label { get; set; }
}
我的DbContext看起来像:
public class MyEventsDataContext : DbContext
{
public MyEventsDataContext()
: base("MyEventsDatabase")
{
// Do nothing.
}
public DbSet<MyEvent> MyEvents { get; set; }
public DbSet<TimeSlot> TimeSlots { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEvent>()
.HasMany<TimeSlot>(e => e.TimeSlots);
}
}
我正在迁移一些默认数据用于测试目的:
protected override void Seed(MyEventsDataContext context)
{
// This method will be called after migrating to the latest version.
var timeSlot1 = new TimeSlot {Label = "Slot 1"};
timeSlot1.Items.Add("Do stuff 1");
timeSlot1.Items.Add("Do stuff 2");
timeSlot1.Items.Add("Do stuff 3");
var timeSlot2 = new TimeSlot {Label = "Slot 2"};
timeSlot2.Items.Add("Do stuff 1");
timeSlot2.Items.Add("Do stuff 2");
timeSlot2.Items.Add("Do stuff 3");
var timeSlot3 = new TimeSlot {Label = "Slot 3"};
timeSlot3.Items.Add("Do stuff 1");
timeSlot3.Items.Add("Do stuff 2");
timeSlot3.Items.Add("Do stuff 3");
context.TimeSlots.AddOrUpdate(new[] {timeSlot1, timeSlot2, timeSlot3});
var event1 = new MyEvent
{
Address = "123 Street Ln",
CampaignId = "abc123",
City = "City",
CreatedDate = DateTime.Now,
EventDate = DateTime.Now,
EventType = "TradeShow",
Name = "Show Name",
ProductInterest = "MyArm",
State = "State",
Zipcode = "12345",
TimeSlots = new Collection<TimeSlot> {timeSlot1, timeSlot2, timeSlot3}
};
context.MyEvents.AddOrUpdate(event1);
var event2 = new MyEvent
{
Address = "321 Street Ln",
CampaignId = "123abc",
City = "City",
CreatedDate = DateTime.Now,
EventDate = DateTime.Now,
EventType = "Conference",
Name = "Show Name",
ProductInterest = "MyArm",
State = "State",
Zipcode = "54321",
TimeSlots = new Collection<TimeSlot> {timeSlot1, timeSlot2, timeSlot3}
};
context.MyEvents.AddOrUpdate(event2);
}
在我的Controller中,当我从DbContext中检索一个事件时,它没有附加TimeSlots(它是空的)。
MyEvent show = mDb.MyEvents.Find(id);
这里的任何建议都将非常感谢。我可能只是没有正确设置映射。
答案 0 :(得分:2)
您必须启用延迟加载
public MyEventsDataContext()
: base("MyEventsDatabase")
{
this.Configuration.LazyLoadingEnabled = true;
}
或者您应该包括该属性。
mDb.MyEvents.Include("TimeSlots").Find(id)