我有一个企业应用程序,它严重依赖存储过程来实现业务逻辑。我正在考虑将前端从Webforms重做到ASP.NET MVC,但我希望不必为每个存储过程编写一个模型(有数百个)。通常情况下,"Get“存储过程不具有与等效"set”存储过程相同的参数,而且通常单个存储过程正在更新多个数据库表。
因此,我的问题是,在这种后端构建ASP.NET MVC应用程序的最佳实践是什么?实体框架会对此起作用吗?我希望我不需要建立100的模型,每个存储过程一到两个.
我也在考虑使用普通的剃须刀网页和webdata的动态数据行模型,这可能是一个更好的选择。但是,我不能使用像Kendo这样整洁的东西(我认为)。
谢谢你提前给我的智慧。
发布于 2016-04-18 19:34:40
您不需要为每个存储过程建立模型。
这完全取决于你想做什么。
当我使用存储的proc将数据保存到db时,我为要保存的每个值发送参数。
当从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调用。这可能不是你的问题,而是个人的喜好。
就实体框架而言,我缺乏经验,但我认为实体框架+存储proc是个坏主意。
希望这能让你更清楚
发布于 2016-04-18 19:33:59
实体框架将在这方面帮助您。我建议先从数据库执行代码。我不建议使用MVC和Razor。我只需要为业务逻辑构建一个库层(这个层将使用您的存储过程)和服务层进行通信(这个层将只处理与客户端的通信,并将使用该库获取或设置数据)。对于客户端,我将使用普通的HTML和JavaScript,并使用Ajax调用来使用服务。
如果您的公司有支持网络套接字的服务器,我甚至会使用SignalR集线器,而不是服务层的WebApi。
https://stackoverflow.com/questions/36702608
复制相似问题