[英]Execute stored procedure with optional returned columns in EF Core 3.1
[英]Execute stored procedure and using returned information in cshtml
我之前关于这个主题的问题很少有人提出,因此我想首先提出一个更简洁的问题,这实际上是我问题的核心。 在我的.cs模型中,我必须调用一个存储过程,该存储过程调出每个项目的任务数。
我需要的特定内容是每个项目可能具有的任务数量,该数量作为sp参数UnfinishedTaskCount返回。
我的cshtml文件中的剃刀将显示返回的信息,这是我设法弄清楚的另一个问题,但是获得所需的信息是最后的障碍。 这是.cs文件中的代码,我需要对存储过程进行正确的调用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
namespace IntelliBase.Models
{
public partial class Project:Description
{
....
private int unfinishedtasks;
public int UnFinishedTaskCount
{
get
{
SqlConnection sqlConnection1 = new SqlConnection("Data Source=ORLANDOSQL1;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
Object returnValue;
cmd.CommandText = "mp_Display_Projects_Home";
cmd.Parameters.Add("@BeginPage", SqlDbType.VarChar).Value = 0;
cmd.Parameters.Add("@EndPage", SqlDbType.VarChar).Value = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
returnValue = cmd.ExecuteScalar();
sqlConnection1.Close();
return unfinishedtasks = (int)returnValue;
}
set { ; }
}
}
}
ExecuteScalar命令只会带回第一行信息,这无济于事,因为有更多行项目都有各自的任务集,而且我读到ExecuteNonQuery不会返回特定的参数,而只是返回所有数据。 我不需要所有数据,只需每个项目的UnfinishedTaskCount。
因此,由于有ExecuteScalar,它为表中所有项目的任务数返回“ 2”,因为第一行中的项目有两个任务(其他项目的任务数不同)。 是否有另一个Execute--调用将为每个项目获取正确数量的任务,以便我可以在cshtml上正确显示它们? 我感谢大家的耐心; 这是我的第一个大型C#项目,我很想让它正常工作。
这里有几个问题:
ExecuteReader
而不是ExecuteScalar
。 您的代码中有几个实现IDisposable
对象,所以它们应该在using
块中:
using (SqlConnection sqlConnection1 = new SqlConnection( "Data Source=ORLANDOSQL1;Integrated Security=True")) { using (SqlCommand cmd = new SqlCommand()) { using (var reader = cmd.ExecuteReader()) { while (reader.Read() { // Create an instance of your model object, // fill it from the reader, then add it to the collection // of model objects } } } }
假设您的模型对象称为“产品”,并且具有两个属性,即“ ID”和“ NumberOfUnfinishedTasks”。 假设您的SP返回了一组{ID,NumberOfUnfinishedTasks}。 然后
List<Product> products = new List<Product>();
while (reader.Read()
{
// Create an instance of your model object,
Product product = new Product();
// fill it from the reader
product.ID = (int) reader["ID"];
product.NumberOfUnfinishedTasks = (int) reader["NumberOfUnfinishedTasks"];
// then add it to the collection
// of model objects
products.Add(product);
}
后来:
return View(products);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.