alex
alex

Reputation: 720

Entity framework : Including related entities on double related objects

I'm using entity frameworks. I have this situation :

Obj1: ( ID (Primary key ) , name )
Obj2: ( ID ( Primary key ) , FromID ( foreign key obj1) , ToID (foreign key obj1) , quantity  )

So there are 2 relation between obj1 and obj2. I want to select all obj2 and all related from obj1. How should I include :

1. context.obj2.Include("FromID").Tolist   
or
2.context.obj2.include ("FromID").Include("ToID").Tolist 

because the collection FromID and ToID may have all or some identical items.

Thank you !

Upvotes: 0

Views: 59

Answers (1)

John Castleman
John Castleman

Reputation: 1561

So, in your Entity Framework POCOs, your model classes - as you describe them - would look something like this:

public class Obj1
{
    public int ID { get; set;}
    public string name { get; set; }
}

public class Obj2
{
    public int ID { get; set; }
    public int FromID { get; set; }
    public int ToID { get; set; }
    public int quantity { get; set; }
}

The keys you describe would indicate the following additions, using Data Annotations:

public class Obj1
{
    [Key]
    public int ID { get; set;}
    public string name { get; set; }
}

public class Obj2
{
    [Key]
    public int ID { get; set; }
    public int FromID { get; set; }
    public int ToID { get; set; }
    public int quantity { get; set; }
}

You don't mention any Navigation Properties explicitly in your model, but the fact that you wish to use Include implies that you want some ... I'm going to add some for each Foreign Key relationship you listed, with Navigation Properties on both sides of the relation - see InverseProperty and ForeignKey (attributes):

public class Obj1
{
    public Obj1
    {
        Froms = new List<Obj2>();
        Tos = new List<Obj2>();
    }

    [Key]
    public int ID { get; set;}
    public string name { get; set; }

    [InverseProperty("From")]
    public virtual ICollection<Obj2> Froms { get; set; }

    [InverseProperty("To")]
    public virtual ICollection<Obj2> Tos { get; set; }
}

public class Obj2
{
    [Key]
    public int ID { get; set; }
    public int quantity { get; set; }

    public int FromID { get; set; }
    [ForeignKey("FromID")]
    public virtual Obj1 From { get; set; }

    public int ToID { get; set; }
    [ForeignKey("ToID")]
    public virtual Obj1 To { get; set; }
}

So, now that we have all the model classes set up, we can see that your relationship - being 1-to-many - would actually require the Include only when going the other way:

var obj1sWithAllFromsAndTos = context.Obj1s
                                     .Include(o => o.Froms)
                                     .Include(o => o.Tos)
                                     .ToList();

as opposed to

var obj2s = context.Obj2.ToList();

which would already include each related Obj1 in its From and To properties.

Upvotes: 1

Related Questions