您不需要为每个存储过程创建一个模型。
这一切都取决于你想做什么。
当我使用存储过程将数据保存到数据库时,我会为每个要保存的值发送参数。
从 db 获取值时,我使用模型。您在这里使用的模型显然取决于您,如果您正在接收文件数据,那么您可以拥有 FileModel、imageData、ImageModel 等。
例子:
我为此使用管理器和服务类:
public void UpdateCustomerCredentials(long id, string firstName, string lastName, string email, string mobilePhoneNumber, int price, string notes, Guid? imageId = null)
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("UpdateCustomer", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Id", id));
cmd.Parameters.Add(new SqlParameter("@FirstName", firstName));
cmd.Parameters.Add(new SqlParameter("@LastName", lastName));
cmd.Parameters.Add(new SqlParameter("@Email", email));
cmd.Parameters.Add(new SqlParameter("@MobilePhoneNumber", mobilePhoneNumber));
cmd.Parameters.Add(new SqlParameter("@ImageId", GetParamValue(imageId)));
cmd.Parameters.Add(new SqlParameter("@Price", price));
cmd.Parameters.Add(new SqlParameter("@Notes", notes));
try
{
con.Open();
cmd.ExecuteReader();
con.Close();
}
catch (SqlException ex)
{
cmd.Dispose();
throw ex;
}
finally
{
cmd.Dispose();
}
}
}
}
使用客户模型获取数据:
public List<Customer> GetAllCustomers()
{
List<Customer> customers;
SqlDataReader sqlDataReader = null;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("GetAllCustomers", con))
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
sqlDataReader = cmd.ExecuteReader();
customers = (from x in sqlDataReader.Cast<DbDataRecord>()
select new Customer
{
Id = GetValue<long>("Id", x),
ProfileImageId = GetValue<Guid?>("ImageId", x),
ContentType = GetValue<string>("ContentType", x),
FirstName = GetValue<string>("Name", x),
LastName = GetValue<string>("LastName", x),
Email = GetValue<string>("Email", x),
PhoenNumber = GetValue<string>("MobilePhoneNumber",x)
}).ToList();
sqlDataReader.Close();
}
catch (SqlException ex)
{
if (sqlDataReader != null) sqlDataReader.Close();
cmd.Dispose();
throw ex;
}
finally
{
if (sqlDataReader != null) sqlDataReader.Dispose();
cmd.Dispose();
}
}
}
return customers;
}
我个人喜欢使用 classLibraries 进行 SQL 调用。这可能超出了您的问题,而是个人喜好。
就实体框架而言,我缺乏经验,但我认为实体框架 + 存储过程是一个坏主意。
希望这能让你更清楚