具有工作单元的存储库模式是否最适合实体框架应用程序?

我正在创建一个新的asp.net mvc应用程序,我想使用存储过程(Microsoft企业库)而不是实体框架(或任何其他ORM)。

那么,如何在MVC应用程序中使用存储库模式?

我浏览了许多教程,但没有得到预期的结果。请为我建议更好的方法用于n层应用程序。

最佳答案

您必须了解“存储库模式”只是组织代码的一种主意。我认为您仍然可以毫无问题地使用它。

我只想为您提供一个使用sql存储过程的实现示例:假设您必须管理经典表“ Contacts”。

您可以创建您的UnitOfWork合同:

public interface IContactsRepository {
 void AddContact(Contact c);
 void RemoveContact(Contact c);
 void UpdateContact(Contact c);
 void Search(string keyword);
}


之后,您可以不使用EF来创建自己的实现:

public sealed class SPContactsRepository : IContactsRepository {
 // Is just an exampl.e
 public void AddContact(Contact c) {
   var sqlCommnad = new SqlCommand(this._connectionString);
   sqlCommand.CommandText = "dbo.AddContact";
   sqlCommand.CommandType = CommandType.StoredProcedure;
   sqlCommand.AddParameter("Name", c.Name);
   sqlCommand.Connection.Open();
   sqlCommand.ExecuteNonQuery();

 }
}


希望对您有所帮助!

09-04 11:00
查看更多