我想使用Linq将以下两个类结果组合在一起并在视图上显示结果?
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("ProductMaster")]
public partial class ProductMaster
{
public ProductMaster()
{
ProductDetails = new HashSet<ProductDetail>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ProductId { get; set; }
[StringLength(50)]
public string ProductName { get; set; }
public virtual ICollection<ProductDetail> ProductDetails { get; set; }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class ProductDetail
{
public int? Price { get; set; }
[StringLength(50)]
public string ManufactureBy { get; set; }
public int? ProductId { get; set; }
[Key]
public int ProdDetailsId { get; set; }
public virtual ProductMaster ProductMaster { get; set; }
}
使用LINQ Query连接两个表数据。
public ActionResult BindProductMasterData()
{
Model1 db = new Model1();
var varResult = from pm in db.ProductMasters join pd in db.ProductDetails on pm.ProductId equals pd.ProductId select new { pm.ProductId, pm.ProductName, pd.Price, pd.ManufactureBy };
return View(varResult.ToList());
}
在View中显示下表列数据 ProductId,ProductName,Price,ManufactureBy
答案 0 :(得分:0)
为此视图创建一个视图模型,并将LINQ连接查询结果分配给该列表并将其传递给视图。
/usr/local/etc/php/7.0/php.ini
并在您的操作方法中,将LINQ查询的结果投影到ProductVm对象列表。
public class ProductVm
{
public int Id { set;get;}
public string Name { set;get;}
public List<ProductDetailVm> Details { set;get;}
}
public class ProductDetailVm
{
public int Id { set;get;}
public int? Price { get; set; }
public string ManufactureBy { get; set; }
}
现在确保您的视图强烈输入到我们的ProductVm视图模型列表
public ActionResult BindProductMasterData()
{
Model1 db = new Model1();
var varResult = db.ProductMasters
.Select( f =>
new ProductVm
{
Id = f.ProductId,
Name = f.ProductName,
Details = f.ProductDetails.Select(g => new ProductDetailVm
{
Id = g.ProdDetailsId ,
Price = g.Price,
ManufactureBy = g.ManufactureBy
}
).ToList()
}).ToList();
return View(varResult);
}