Chris
Chris

Reputation: 3129

How to join two entity objects together?

I took a look around for an answer to this and what I have found is similar to what I am doing but not getting it quite right. I can join two entities when they are lists but not when they are singular objects. I am not sure if this makes sense

Here I have two entity objects

Location location = VIPEF.Locations
    .Where(w => w.LocationID == id).FirstOrDefault<Location>();
Contact contact = VIPEF.Contacts
    .Where(w => w.ContactID == location.ContactID).FirstOrDefault<Contact>();

But when I go to write a query:

var query = from a in location
            join b in contact on a <-- Thats where I get a problem

once I go to join the two I can't get the ID from location, and the only option i get is a.equals and not a.LocationID as I think I should be getting.

What am I doing wrong here?

Upvotes: 1

Views: 2814

Answers (1)

DavidG
DavidG

Reputation: 118937

You don't need Linq to join two objects together, you just need to compose a new object. It's fairly simple using object initialiser syntax:

var thing = new Thing //<-- Your class that has the combined properties you need
{
    LocationID = location.LocationID, 
    LocationName = location.Name,
    ContactName = contact.Name,
    ContactAddress = contact.Address,
    //etc...
};

Alternatively, you can do this all in one go rather than 2 queries and then the composition:

var things = from l in VIPEF.Locations
             join c in VIPEF.Contacts on l.ContactID equals c.ContactID
             where l.LocationID == id
             select new Thing
             {
                 LocationID = location.LocationID, 
                 LocationName = location.Name,
                 ContactName = contact.Name,
                 ContactAddress = contact.Address,
                 //etc...
             };

This will give you an IEnumerable<Thing> to play with though it may only have a single entry.

Upvotes: 3

Related Questions