Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何在实体框架中迭代联接查询?_Sql_Entity Framework_Asp.net Mvc 3 - Fatal编程技术网

Sql 如何在实体框架中迭代联接查询?

Sql 如何在实体框架中迭代联接查询?,sql,entity-framework,asp.net-mvc-3,Sql,Entity Framework,Asp.net Mvc 3,这是我的控制器: public ActionResult Index() { DBContext_Model db = new DBContext_Model(); var srmas = ( from SRMAs in db.SRMAs join SRMAStatus in db.SRMAStatus on SRMAs.

这是我的控制器:

public ActionResult Index()
        {
            DBContext_Model db = new DBContext_Model();
            var srmas = (
                            from SRMAs in db.SRMAs
                            join SRMAStatus in db.SRMAStatus on SRMAs.Id equals SRMAStatus.Id
                            join PurchaseOrders in db.PurchaseOrders on SRMAs.PONumber equals PurchaseOrders.PONumber
                            join Suppliers in db.Suppliers on PurchaseOrders.SupplierID equals Suppliers.SupplierID
                            select new {SRMAs.Id,SRMAs.PONumber,SRMAs.CreatedOn,Suppliers.SupplierName,SRMAStatus.StatusName,PurchaseOrders.PODate,PurchaseOrders.suppliersOrderNumber}
                        ).ToList();
            ViewBag.SRMAs = srmas;
            return View();
        }

现在我需要迭代结果。我应该使用什么类型来强制转换循环变量以获取所需字段?

您将从该查询中获得一个无注释的类型列表。无法强制转换为注释性类型,因为它仅存在于运行时中

克服此问题的最佳方法是创建ViewModel类。一个仅用于数据传输的持久性类:

public class IndexViewModel
{
    public int SRMAsId { get; set; }
    public int PONumber { get; set; }
    // ...
}
使用此选项,您可以选择此类的新实例:

ViewBag.SRMAs = srmas.Select(srma => new IndexViewModel
                                     {
                                         SRMAsId = srma.Id,
                                         PONumber = srma.PONumber,
                                         // ...
                                     }).ToList();