1
votes

I'm new to Entity Framework. :-)
I have something similar to the following:

Master Table
------------------------------------
Id: Name: Detail_id:
1 MasterOne 1
2 MasterTwo 2

Details Table:
------------------------------------
Id: Name: Type:
1 Detail_1 1
2 Detail_2 1
3 Detail_3 2

The Details table has a flag ('Type') that differentiates between the record types.

My Master object looks like this:

public class Master
{
public int ID { get; set; }
public string Name { get; set; }
public virtual IEnumerable<Detail> Details { get; set; }
}

My Master table needs to load its detail records but ONLY those with a flag of '1'.

My problem is that the IEnumerable Details property pulls in ALL detail records, whereas I need it to only pull in those detail records with a Type flag = 1.

Is this possible?
Thanks!!

2

2 Answers

0
votes

Assuming you are using EF 4.1

If you are loading only 1 Master record you can load filtered list of Details as follows.

using (var context = new MyContext())
{
    var master = context.Masters.Find(1);

    context.Entry(master)
        .Collection(m => m.Details)
        .Query()
        .Where(d => d.Type == 1)
        .Load();

    //do stuff with master

}

You can go through Using DbContext in EF 4.1 Part 6: Loading Related Entities to learn more about this.

0
votes

You can try:

var master = (ctx.Masters.Where(x => x.ID == 1)).FirstOrDefault();
var details = master.Details.Where(x=>x.Type == 1);