简体   繁体   中英

Entity Framework database-first: accessing 2 foreign keys names from same table

I have two tables - one is the Customer table which has 2 columns which are both foreign keys to the Cars table.

Customer table:

xid  Name    Prev_CarID(fk Cars)  Current_CarID(fk Cars)
--------------------------------------------------------
1    Ben        2                      1
2    Frank      1                      3
3    John       3                      2

Cars table

id   Name    
-------------
1    Ford
2    BMW
3    Volvo

I am trying to get the following result

CustomerName PreviousCar  CurrentCar
-------------------------------------
Ben             BMW          Ford
Frank           Ford         Volvo
John            Volvo        BMW

In my method I wrote code like this:

var result = Context.Customers
                    .Select(o => new Models.Customers()
                                     {
                                         Name = o.Name,
                                         PreviousCar = o.Cars.Name,
                                         CurrentCar = o.Cars.Name,
                                     })
                    .ToList();

I'm not getting the correct values.

How do I get the correct values for this?

could you use joins?

   var result = from customers in context.customers
    join previousCar in context.cars on customers.prevCarId equals previousCar.Id
    join currentCar in context.cars on customers.currentCarId equals currentCar.Id
    select new
    { Name = customers.Name,
      PreviousCar = previousCar.Name,
      CurrentCar = currentCar.Name
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM