Reputation: 5627
Getting what I think is an odd behaviour in EF, which I'm hoping someone can shed some light on. Basicaly, if I retrieve an item with a foreign key, the foreign key item isn't retrieved? This seems like a bit of a short coming. Have I missed something obvious or is there a pattern to deal with this?
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);
}
}
}
Upvotes: 1
Views: 149
Reputation: 5627
Related properties need to either be 'eagerly loaded' or 'lazy loaded' (see Charlino's answer).
To eagerly load, the code needs to make use of the 'Include' extension.:
var foos = from m in context.Foo.Include("MyBar")
select m;
Upvotes: 0
Reputation: 15890
For lazy loading you need to make your related properties virtual.
E.g.
public virtual Bar MyBar { get; set; }
Upvotes: 2