Hi mukesh1,
mukesh1 says:
join st
in
db.States on st.State_id equals u.State
Change the above with the below code.
join st in db.States on u.State equals st.State_id
Check this example. Now please take its reference.
Database
For this example I have used of NorthWind database that you can download using the link given below.
Download Northwind Database
Model
public class ProductModel
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public decimal? UnitPrice { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
NorthwindEntities entities = new NorthwindEntities();
var products = new List<ProductModel>();
products = (from p in entities.Products
join c in entities.Categories on p.CategoryID equals c.CategoryID
orderby p.ProductID
select new ProductModel
{
ProductID = p.ProductID,
ProductName = p.ProductName,
UnitPrice = p.UnitPrice,
CategoryName = c.CategoryName,
Description = c.Description
}).Take(10).ToList();
return View(products);
}
}
View
@using _EntityFramework_Join_MVC.Models;
@model IEnumerable<ProductModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table class="table">
<tr>
<th>@Html.DisplayNameFor(model => model.ProductID)</th>
<th>@Html.DisplayNameFor(model => model.ProductName)</th>
<th>@Html.DisplayNameFor(model => model.UnitPrice)</th>
<th>@Html.DisplayNameFor(model => model.CategoryName)</th>
<th>@Html.DisplayNameFor(model => model.Description)</th>
</tr>
@foreach (ProductModel item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.ProductID)</td>
<td>@Html.DisplayFor(modelItem => item.ProductName)</td>
<td>@Html.DisplayFor(modelItem => item.UnitPrice)</td>
<td>@Html.DisplayFor(modelItem => item.CategoryName)</td>
<td>@Html.DisplayFor(modelItem => item.Description)</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Here my join query is like below.
join c in entities.Categories on p.CategoryID equals c.CategoryID
But if i chnage with below it will give you the runtime error as Error
The name 'c' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.
join c in entities.Categories on c.CategoryID equals p.CategoryID