简体   繁体   中英

asp.net entity framework code first foreign key not retrieve

I'm trying to retrieve company with trades. I have included the entites and the retrieve method. As shown, the companies are inside trades already.

//company entity
public class Companies
{
  public int id { get; set; }
  public string companyID { get; set; }
  public string companyName { get; set; }
  public bool companyMointor { get; set; }   
}

//trade entity
public class Trade
{
  public int id { get; set; }
  public DateTime tradeDate { get; set; }
  public double tradePrice { get; set; }
  public int tradeQuantity  { get; set; }
  public Companies tradeCompany { get; set; }
  public int type { get; set; }

  public types tradeType 
  {
    get { return (Entities.types)type; }
    set { type = (int) value; }
  }
}

//methods to retrieve
public List<Trade> getTrade()
{
  List<Trade> trades = (from t in dbContext.trades
                        orderby t.tradeDate descending             
                        select t).ToList();
  return trades;
}

Use the Include method to eager load navigational properties.

public List<Trade> getTrade()
{
    List<Trade> trades=dbContext.trades.Include(t => t.tradeCompany)
      .OrderBy(t => t.tradeDate).ToList();

    return trades;
}

Edit: If you are using ObjectContext API try the following

public List<Trade> getTrade()
{
    List<Trade> trades=dbContext.trades.Include("tradeCompany")
      .OrderBy(t => t.tradeDate).ToList();

    return trades;
}

change your gettrade method to have an include line:

//methods to retrieve 
    public List<Trade> getTrade() 
    { 
        List<Trade> trades=(from t in dbContext.trades 
                .Include("tradeCompany")
                orderby t.tradeDate descending 

                select t).ToList(); 
        return trades; 
    } 

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