1
获得我认为是EF中一个奇怪的行为,我希望有人能够阐明一些。基本上,如果我用外键检索一个项目,外键项目不被检索?这似乎有点短暂。我是否错过了一些显而易见的内容,或者是否存在处理这种问题的模式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);
}
}
}