【问题标题】:Joining two a ViewModel加入两个 ViewModel
【发布时间】:2020-03-12 10:55:48
【问题描述】:

这是模型:

public class ProCar
{

    public string ProductName { get; set; }

    public int ProductYear { get; set; }

    public string CarBrand { get; set; }

    public int CarEngine { get; set; }

}

我正在使用这个 LINQ。如何保存到 ProCar 列表。

List<Product> p1 = db.Products.ToList();
List<Car> c1 = db.Cars.ToList();
List<ProCar> query = from pList in p1 
join cList in c1 on pList equals cList.ProductId 
select new { ProductName = pList.ProductName, ProductYear = pList.ProductYear, CarBrand = cList.CarBrand, CarEngine = cList.CarEngine };
return View();

找不到问题。

【问题讨论】:

    标签: asp.net asp.net-mvc linq


    【解决方案1】:

    假设您在 ProductCar 之间有关系:

    var query = from product in db.Products
                join car in db.Cars on product.Id equals car.ProductId//The relation between car and product
                select new ProCar
                {
                    ProductName = product.ProductName,
                    ProductYear = product.ProductYear,
                    CarBrand = car.CarBrand,
                    CarEngine = car.CarEngine
                };
    
    List<ProCar> proCarList = query.ToList();
    

    Join Clause

    【讨论】:

      【解决方案2】:

      您正在创建一个匿名列表类型,它无法找到/转换 ProCar 的列表类型。因此,您需要指定紧密耦合模型绑定,如下所示

      List<ProCar> query = ( from pList in p1 
      join cList in c1 on pList equals cList.ProductId 
      select new ProCar
       {
             ProductName = product.ProductName,
             ProductYear = product.ProductYear,
             CarBrand = car.CarBrand,
             CarEngine = car.CarEngine
      }).ToList();
      

      【讨论】:

        猜你喜欢
        • 2019-03-30
        • 1970-01-01
        • 1970-01-01
        • 2015-02-07
        • 2016-06-16
        • 1970-01-01
        • 2017-05-28
        • 1970-01-01
        • 2013-10-17
        相关资源
        最近更新 更多