【问题标题】:Linq MVC with view model带有视图模型的 Linq MVC
【发布时间】:2014-09-30 20:19:24
【问题描述】:

我对 ASP.NET/MVC/LINQ 非常陌生。我的数据库中有三个表,我的解决方案中有它们对应的模型:

salesperson
  id
, name
, address
, dob

sales
  id
, shopid
, salespersonid
, productid
, AmountSale
, saleDate

Shop
  id
, shopName
, Location

我还有一个存储过程,它将为所有销售人员返回以下数据:

  SalesPersonid
, TotalAmount_Sale
, Most_Recent_ShopName
, Count_Of_sales_Lifetime
, count_of_sales_ThisMonth

如何使用 LINQ 调用存储过程并在前端显示数据?到目前为止,我看到的所有样本都返回了一个已经存在的模型。我很困惑,请帮忙。

【问题讨论】:

  • 你在使用任何一种 ORM 吗? (实体框架、NHibernate 等)
  • 你需要使用存储过程吗?
  • 通常你不会使用存储过程,你通常会使用实体框架 ORM。 Calling stored procedures with Entity Framework 是绝对可能的,但通常你很少这样做,而且只是为了优化特定情况。

标签: asp.net-mvc linq asp.net-mvc-4 razor viewmodel


【解决方案1】:

假设您不介意添加一个库:

首先,安装Dapper dot Net。然后,建立一个模型来存储你的结果:

class MySprocResult
{
  public int SalesPersonid { get; set; }
  public decimal TotalAmount_Sale { get; set; }
  public string Most_Recent_ShopName { get; set; }
  public int Count_Of_sales_Lifetime { get; set; }
  public int count_of_sales_ThisMonth { get; set; }
}

接下来建立数据库连接,使用Dapper dot net返回结果:

String connectionString = "connectionString";
using (IDbConnection db = new System.Data.SqlClient.SqlConnection(connectionString))
{
    // Open SQL connection
    db.Open();

    // Fetch results from stored procedure
    IEnumerable<MySprocResult> results = db.Query<MySprocResult>(
        "mySprocName",                           // stored procedure name

        //--- OPTIONAL
        //param: new { id = 123 },               // pass parameters if necessary
        //--- /OPIONAL

        commandType: CommandType.StoredProcedure // tell dapper it's a SPROC
    );

    // Close SQL connection
    db.Close();

    /* work with "results" here */
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多