代码之家  ›  专栏  ›  技术社区  ›  Kieran Senior

带有LINQ和ASP.NET MVC的存储过程多表输出

  •  2
  • Kieran Senior  · 技术社区  · 16 年前

    我们的系统经常调用存储过程,这些存储过程会输出多个值为结果的表。以前,我们使用XML输出来获取每个表,并使用XSLT将它们正确地关联起来。如果我使用ASP.NET MVC和LINQ调用存储过程,如何获取每个表,然后根据需要输出数据?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Community CDub    8 年前

    this article here 解释一切。这是我链接的同一篇文章,在你的 previous SO question .

        2
  •  3
  •   Ole Lynge    16 年前

    这里有一篇关于Linq to SQL和存储过程的文章,特别是“处理存储过程中的多个结果形状”一节: LINQ to SQL - Retrieving Data Using Stored Procedures .

    这对你的案子有用吗?

    否则,不使用linq to sql,可能使用 SqlDataReader NextResult 要查看结果,例如:

    IList<Employee> employees = new List<Employee>();
    IList<Customer> customers = new List<Customer>();
    using (SqlConnection connection = new SqlConnection
        (Properties.Settings.Default.NorthwindConnectionString))
    using (SqlCommand command = new SqlCommand
        ("GetEmployeesAndCustomers", connection))
    {
        command.CommandType = CommandType.StoredProcedure;
        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                Employee e = new Employee{EmployeeID = (int)reader["EmployeeID"]};
                employees.Add(e);
            }
            reader.NextResult();
            while (reader.Read())
            {
                Customer c = new Customer{CustomerID = (string)reader["CustomerID"]};
                customers.Add(c);
            }
        }
    }
    

    编辑:如何处理不容易适应域模型对象的自定义数据组合的示例;在本例中,检索订单以及订单的客户:

    namespace Company.Application.ViewModel
    {
        public class CustomerOrder
        {
            public string CustomerID { get; set; }
            public string CustomerName { get; set; }
            public int OrderID { get; set; }
            public DateTime? OrderDate { get; set; }
        }
    }
    namespace Company.Application.Repository
    {
        public class CustomerOrderRepository
        {
            public IList<CustomerOrder> GetCustomerOrders()
            {
                NorthwindDataContext db = new NorthwindDataContext();
                var custorders = from customer in db.Customers
                                 join order in db.Orders
                                 on customer.CustomerID equals order.CustomerID
                                 select new CustomerOrder
                                 {
                                     CustomerID = customer.CustomerID,
                                     CustomerName = customer.CompanyName,
                                     OrderID = order.OrderID,
                                     OrderDate = order.OrderDate
                                 };
                return custorders.ToList();
            }
        }
    }
    

    灵感来源:在 chapter 关于 NerdDinner ScottGuthrie谈到了如何创建自定义的“ViewModel”对象来保存来自连接的数据,例如那些不容易放入域模型对象的连接。

    推荐文章