简体   繁体   中英

Entity Framework Join two tables together for displaying in MVC view

I am new to Entity Framework and LINQ and I am having some difficulty in linking two tables together for a view so that it can be displayed to the end user. I have a list of prices which are displayed in Euro in one table and in the other table I have an exchange rate table. Currently this is only displayed in Euro and I would like to display this in GBP.

Previously I was able to return the single view table from my controller using the following:

return View(db.Prices.ToList());

Now that I am attempting to return the two tables I am not sure what I need to do but I have tried the following code to join the tables:

var result = (from a in db.Prices
              join b in db.ExchangeRatse on a.TRADE_DATE equals b.TRADE_DATE

The Prices class does not have a column for GBP price so I need to multiply the euro price by the exchange rate for the trading day and display this in my view but the backing model of the view is set to Prices, would I be better to come up with a view model for this or could it be done simpler?

You need something like:

var result = (from a in db.Prices
          join b in db.ExchangeRatse on a.TRADE_DATE equals b.TRADE_DATE)
          .Select(x => new {
          PriceInEuro = x.a.PriceInEuro,
          PriceInSterling = x.a.PriveInEuro * x.b.ExchangeRate})
          .ToList();

Warning - not tested.

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