Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5524

How to map a relation in entity framework

I have 3 tables

=================    =================    =================
| TableA        |    | RelationAC    |    | TableC        |
=================    =================    =================
| IdA           |    | Id            |    | IdC           |
|               |    | IdA           |    |               |
| Field1A       |    | IdC           |    | Field1C       |
=================    =================    =================

And this are my model's code:

public partial class TableA
{
    public TableA()
    {
       this.RelationAC = new HashSet<RelationAC>();
    }

    [Key]
    public decimal IdA { get; set; }
    public string Field1A { get; set; }
    [ForeignKey("IdA")]
    public virtual ICollection<RelationAC> RelationAC { get; set; }
}

public partial class TableC
{
    [Key]
    public decimal IdC { get; set; }
    public string Field1C { get; set; }
}


public partial class RelationAC    
{
    public RelationAC    ()
    {
        this.TableC= new HashSet<TableC>();
    }
    [Key]
    public decimal Id { get; set; }
    public decimal IdA{ get; set; }
    public decimal IdC{ get; set; }

    [ForeignKey("IdC")]
    public virtual ICollection<TableC> TableC { get; set; }
}

If made this query

var query = from d in db.TableA 
            select d;


foreach( TableA  ta in query.Tolist())
{
    foreach(RelationAC rac in ta.RelationAC.Tolist())
    {
        TableC tc = rac.TableC.First(); // It allways has count = 0 , even my db has data
    } 
}

Why TableC tc is allways empty ?

Upvotes: 0

Views: 88

Answers (1)

Mark Oreta
Mark Oreta

Reputation: 10416

Your property is probably having issues w/ lazy loading. Try eager loading the collection:

db.TableA.Include("RelationAC.TableC")

Upvotes: 1

Related Questions