我是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调用存储过程并在前端显示数据?到目前为止,我见过的所有样本都返回了已存在的模型。我很困惑,请帮助。
答案 0 :(得分:2)
假设您不介意在混音中添加库:
首先,安装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 */
}