user2987995
user2987995

Reputation: 140

Getting list of records from foreign keys of another table

I am new to entity framework and am trying to get the entity models from a foreign key of another table. The code below is how I know to get a list of models, but I don't want the models that have the fk1. I want the models of those models foreign key references. I know I can iterate over those models after getting the list and access the foreign key from there, but what is the proper way to grab them from entity at once?

List<Entity.Models.myModel> myModels = context.myModels
  .Where(r => r.fk1 == fk1) 
  .ToList();

what I want is a list of myModels[i].foreignKey2. Sorry for the confusion.

Upvotes: 1

Views: 6168

Answers (2)

Slauma
Slauma

Reputation: 177133

Maybe you are looking for something like this:

Given an Order entity with a reference to a ShippingType and a Customer...

public class Order
{
    public int OrderId { get; set; }
    public int ShippingTypeId { get; set; }
    public ShippingType ShippingType { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
}

...you want to retrieve all customers that have orders with a given shipping type ID. Then the query could look like this:

List<Customer> customers = context.Orders
    .Where(o => o.ShippingTypeId == givenShippingTypeId) // your fk1
    .Select(o => o.Customer) // your foreignKey2 ???
    .Distinct() // To eliminate duplicate customers in the result
    .ToList();

Upvotes: 2

bto.rdz
bto.rdz

Reputation: 6720

If I understood what you need is this:

db.myModels.Include("myForeignModel").Where(r => r.name.contains("h")).toList

what this will return is a list of models wich name contains 'h' and all these models will have a foreing model loaded for eaxample

public class Parent
{
    public int id {get; set;}
    public string name {get;set;}
    public int childId {get;set;
    public virtual child child {get;set;}
}

public class child
{
   public int id {get; set;}
   public string name {get;set;}

}

now let's say you have a table for parents and another one for children

public dbset<parent> parents {get;set;}
public dbset<child> children {get;set;}

now what if you want to get the first child name of a parent that is called 'john' you will do this query

var db = new mycontext()

var parent = db.parents.include("child").Where(p => p.name == "john").FirstorDefault();

parent.child.name //this will show the child name for the parent called john

Upvotes: 0

Related Questions