开发者

Loading associations in RIA Services + Entity Framework Code-First

I have just transferred my EF 4.0 Solution to use EF 4.1 Code-First. Everything went smooth and I was able to get data from DB and show it in my Silverlight project using WCF RIA Services 1.0SP2-RC in a couple of hours.

The only problem occurs when I'm trying to load references in my domain service. I have added the [Include] attribute to my reference property. Also, I have enabled Lazy Loading for my DbContext.But still, the following method returns nothing (The following worked on Ef 4.0 but not on 4.1):

public IEnumerable<Bar> GetBarsInFoo (int fooId, bool direction)
{
    var foo = this.DbContext.Foos.FirstOrDefault(f => f.FooId == fooId);
    var Bars = foo.Bars.Where(b => b.Direction == direction).ToList();
    return Bars;
}  

So I have to check and see if the referenced collection is not included, then load it:

public IEnumerable<Bar> GetBarsInFoo (int fooId, bool direction)
{
    var foo = this.DbContext.Foos.FirstOrDefault(f => f.FooId == fooId);

    // Additional code to load the relation.
    if (!this.context.Entry(foo).Collection(f => f.Bars).IsLoaded)
    {
        this.context.Entry(foo).Collection(f => f.bars).Load();   
开发者_C百科    }

    var Bars = foo.Bars.Where(b => b.Direction == direction).ToList();
    return Bars;
}  

The above code, returns the results correctly.

The problem is that I have to change many parts of my code if I want to handle this problem as I have mentioned.

Here's my entities definitions:

public partial class Foo
{
    [Key]
    public int FooId {get; set;}

    [Include]
    [Association("Foo_Bar", "FooId", "FooId")]
    [Display(AutoGenerateField = false)]
    public virtual ICollection<Bar> Bars { get; set; }
}

public partial class Bar
{
    [Key]
    public int BarId {get; set;}

    [Display(AutoGenerateField = false)]
    public int FooId { get; set; }

    [Include]
    [Display(AutoGenerateField = false, Name = "In Foo", Order = 12)]
    [Association("Foo_Bar", "FooId", "FooId", IsForeignKey = true)]
    [ForeignKey("FooId")]
    public virtual Foo Foo { get; set; }
}  

Is there any way that I can let EF handle to load relations without me checking?


Assuming you can live without lazy loading, the explicit way to include child objects is to use the Include<T>(...) extension method. In your example,

public IEnumerable<Bar> GetBarsInFoo (int fooId, bool direction)
{
    var foo = this.DbContext.Foos
                            .Include(f => f.Bars)
                            .FirstOrDefault(f => f.FooId == fooId);

    var Bars = foo.Bars.Where(b => b.Direction == direction).ToList();
    return Bars;
}

This is the simplest way to load all of the child objects. As an added bonus, you'll get them in one trip to the database, rather than two.

You may find more relevant information at the ADO.NET team blog though this was for CTP5.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜