得到我认为在EF中的一个奇怪的行为,我希望有人可以阐明。基本上,如果我使用外键检索项目,则不会检索外键项?这似乎有点短暂。我是否遗漏了一些显而易见的事情,或者是否有一种模式可以解决这个问题?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace EFTest
{
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new MCInitializer());
EFTestEM context = new EFTestEM();
var foos = from m in context.Foo
select m;
foreach (var foo in foos)
{
// foo.MyBar is null?! How do I populate it?
Console.WriteLine("{0},{1}",foo.Desc,foo.MyBar.Whatever);
}
}
}
[Table("tbl_Bar")]
public class Bar
{
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BarId { get; set; }
public string Whatever { get; set; }
public string Whenever { get; set; }
}
[Table("tbl_Foo")]
public class Foo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FooId { get; set; }
public string Desc { get; set; }
public int MyBarId { get; set; }
[ForeignKey("MyBarId")]
public Bar MyBar { get; set; }
}
public class MCInitializer : DropCreateDatabaseAlways<EFTestEM>
{
protected override void Seed(EFTestEM context)
{
List<Bar> bars = new List<Bar>
{
new Bar(){Whatever = "Bar1"},
new Bar(){Whatever = "Bar2"},
new Bar(){Whatever = "Bar3"},
};
List<Foo> foos = new List<Foo>
{
new Foo() {Desc = "Foo1", MyBar = bars[0]},
new Foo() {Desc = "Foo2", MyBar = bars[1]},
new Foo() {Desc = "Foo3", MyBar = bars[2]}
};
foreach (var bar in bars)
context.Bar.Add(bar);
foreach (var foo in foos)
context.Foo.Add(foo);
context.SaveChanges();
base.Seed(context);
}
}
}
答案 0 :(得分:2)
对于延迟加载,您需要将相关属性设置为虚拟。
E.g。
public virtual Bar MyBar { get; set; }
答案 1 :(得分:0)
相关属性需要“急切加载”。或者“懒得加载”#39; (见查理的答案)。
要急切加载,代码需要使用&#39; Include&#39;扩展名:
var foos = from m in context.Foo.Include("MyBar")
select m;