在 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);
}
}
}