MVC初体验-EF系列(导航属性)(19)
如果包含外键,会生成导航属性,导航属性的意思就是可以在 分类中获取所有属于该类的商品 ,也可以在商品中获取该类;
导航属性是根据表之间的映射关系自动生成的;
导航属性可以根据当前对象找到一个或者多个对应的其他表中的数据,如果是一对一,使用from直接查询,如果是一对多,使用多from查询,但是注意,多from使用的时候,第二个from查出来的必须是集合类型才能连接;
join in 的用法 on 后面接受条件 equals的左边对象是join左边的查询对象的字段,右边的字段是join右边的查询对象
数据库数据为NorthWind数据库
后台代码:
namespace T1_EF.Controllers { public class ProductsController : Controller { // GET: Products public ActionResult Index() { DbContext db = new NorthwindEntities(); //join查询 var list = from product in db.Set<Products>() join categorie in db.Set<Categories>() on product.CategoryID equals categorie.CategoryID join supply in db.Set<Suppliers>() on product.SupplierID equals supply.SupplierID select new ProductInfoModel { ProductID = product.ProductID, ProductionName = product.ProductName, ProductionCategorie = categorie.CategoryName, ProductuonSupply = supply.CompanyName }; //多from查询的时候,第二个from查出来的必须是集合 //var list = from categores in db.Set<Categories>() // from products in categores.Products join supply in db.Set<Suppliers>() on // products.SupplierID equals supply.SupplierID // select new ProductInfoModel // { // ProductID = products.ProductID, // ProductionName = products.ProductName, // ProductionCategorie = categores.CategoryName, // ProductuonSupply=supply.CompanyName // }; ViewData.Model = list; return View(); } } }
前台代码:
@model IEnumerable<T1_EF.ViewModels.ProductInfoModel> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <table border="1"> <tr> <td>商品ID</td> <td>商品名称</td> <td>商品类别</td> <td>供应商名称</td> </tr> @foreach (var item in Model) { <tr> <td>@item.ProductID</td> <td>@item.ProductionName</td> <td>@item.ProductionCategorie</td> <td>@item.ProductuonSupply</td> </tr> } </table> </div> </body> </html>
新建的自定义类对象:
namespace T1_EF.ViewModels { public class ProductInfoModel { public int ProductID { get; set; } public string ProductionName { get; set; } public string ProductionCategorie { get; set; } public string ProductuonSupply { get; set; } } }
显示效果:
End