当前位置:首页 > 行业动态 > 正文

c#mvc使用存储过程

在C# MVC中,可以通过ADO.NET或Entity Framework来调用存储过程。以下是使用ADO.NET调用 存储过程的示例代码:“ csharp,using (SqlConnection conn = new SqlConnection(connectionString)),{, SqlCommand cmd = new SqlCommand("StoredProcedureName", conn);, cmd.CommandType = CommandType.StoredProcedure;, , // 添加参数, cmd.Parameters.Add(new SqlParameter("@Param1", value1));, cmd.Parameters.Add(new SqlParameter("@Param2", value2));, , conn.Open();, SqlDataReader reader = cmd.ExecuteReader();, , while (reader.Read()), {, // 处理数据, }, , reader.Close();,},

在C# MVC(Model-View-Controller)应用程序中,使用存储过程是一种常见的做法,它可以提高数据访问的效率、安全性和可维护性,以下是如何在C# MVC中使用存储过程的详细步骤:

一、准备工作

1、创建存储过程

登录数据库:使用SQL Server Management Studio或其他数据库管理工具登录到你的数据库服务器。

编写存储过程:根据你的业务需求编写存储过程,创建一个获取用户信息的存储过程:

 CREATE PROCEDURE GetUserById
     @UserId INT
     AS
     BEGIN
         SELECT * FROM Users WHERE UserId = @UserId
     END

2、配置数据库连接字符串

Web.config文件:在ASP.NET MVC项目的Web.config文件中配置数据库连接字符串。

 <connectionStrings>
       <add name="DefaultConnection" connectionString="Server=your_server;Database=your_database;User Id=your_username;Password=your_password;" providerName="System.Data.SqlClient"/>
     </connectionStrings>

二、在C# MVC中使用存储过程

1、创建数据访问层(DAL)

定义接口:定义一个接口来描述数据访问操作,定义一个IUserRepository接口:

 public interface IUserRepository
     {
         User GetUserById(int userId);
     }

实现接口:创建一个类来实现这个接口,并使用SqlConnectionSqlCommand来调用存储过程。

c#mvc使用存储过程

 public class UserRepository : IUserRepository, IDisposable
     {
         private readonly string _connectionString;
         public UserRepository(string connectionString)
         {
             _connectionString = connectionString;
         }
         public User GetUserById(int userId)
         {
             using (var connection = new SqlConnection(_connectionString))
             {
                 var user = new User();
                 var command = new SqlCommand("GetUserById", connection);
                 command.CommandType = CommandType.StoredProcedure;
                 command.Parameters.AddWithValue("@UserId", userId);
                 connection.Open();
                 using (var reader = command.ExecuteReader())
                 {
                     if (reader.Read())
                     {
                         user.UserId = (int)reader["UserId"];
                         user.Username = (string)reader["Username"];
                         // 映射其他属性...
                     }
                 }
                 return user;
             }
         }
         public void Dispose()
         {
             // 清理资源
         }
     }

2、在控制器中使用数据访问层

注入依赖:在控制器中通过构造函数注入或使用依赖注入框架(如Ninject、Unity等)来实例化数据访问层,使用构造函数注入:

 public class UserController : Controller
     {
         private readonly IUserRepository _userRepository;
         public UserController(IUserRepository userRepository)
         {
             _userRepository = userRepository;
         }
         public ActionResult Details(int id)
         {
             var user = _userRepository.GetUserById(id);
             if (user == null)
             {
                 return HttpNotFound();
             }
             return View(user);
         }
     }

3、配置依赖注入

使用Simple Injector:如果你使用的是Simple Injector作为依赖注入框架,可以在App_StartUnityConfig.cs中注册类型映射:

 public static class SimpleInjectorWebApiInitializer
     {
         public static void Initialize()
         {
             var container = new Container();
             container.Register<IUserRepository, UserRepository>(Lifestyle.Scoped);
             DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
         }
     }

在Global.asax中初始化:在Global.asaxApplication_Start方法中调用初始化方法:

 protected void Application_Start()
     {
         SimpleInjectorWebApiInitializer.Initialize();
         // 其他初始化代码...
     }

以下是一个完整的示例,展示了如何在C# MVC中使用存储过程来获取用户信息:

c#mvc使用存储过程

1、存储过程(SQL Server):

 CREATE PROCEDURE GetUserById
   @UserId INT
   AS
   BEGIN
       SELECT * FROM Users WHERE UserId = @UserId
   END

2、Web.config中的连接字符串:

 <connectionStrings>
     <add name="DefaultConnection" connectionString="Server=your_server;Database=your_database;User Id=your_username;Password=your_password;" providerName="System.Data.SqlClient"/>
   </connectionStrings>

3、IUserRepository接口:

 public interface IUserRepository
   {
       User GetUserById(int userId);
   }

4、UserRepository类:

 public class UserRepository : IUserRepository, IDisposable
   {
       private readonly string _connectionString;
       public UserRepository(string connectionString)
       {
           _connectionString = connectionString;
       }
       public User GetUserById(int userId)
       {
           using (var connection = new SqlConnection(_connectionString))
           {
               var user = new User();
              var command = new SqlCommand("GetUserById", connection);
              command.CommandType = CommandType.StoredProcedure;
              command.Parameters.AddWithValue("@UserId", userId);
              connection.Open();
               using (var reader = command.ExecuteReader())
               {
                   if (reader.Read())
                   {
                       user.UserId = (int)reader["UserId"];
                       user.Username = (string)reader["Username"];
                       // 映射其他属性...
                   }
               }
               return user;
           }
       }
       public void Dispose()
       {
           // 清理资源
       }
   }

5、UserController控制器:

 public class UserController : Controller
   {
       private readonly IUserRepository _userRepository;
       public UserController(IUserRepository userRepository)
       {
           _userRepository = userRepository;
       }
       public ActionResult Details(int id)
       {
           var user = _userRepository.GetUserById(id);
           if (user == null)
           {
               return HttpNotFound();
           }
           return View(user);
       }
   }

6、SimpleInjector配置:

c#mvc使用存储过程

 public static class SimpleInjectorWebApiInitializer
   {
       public static void Initialize()
       {
           var container = new Container();
           container.Register<IUserRepository, UserRepository>(Lifestyle.Scoped);
           DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
       }
   }

7、Global.asax中的初始化:

 protected void Application_Start()
   {
       SimpleInjectorWebApiInitializer.Initialize();
       // 其他初始化代码...
   }

四、相关问答FAQs

1、Q: 为什么要使用存储过程而不是直接在代码中写SQL语句?

A: 使用存储过程可以提高性能,因为它们在数据库服务器上预编译和优化,存储过程可以提供更好的安全性,因为SQL注入攻击的风险较低,存储过程可以使代码更加模块化和可维护。

理由: 性能提升、安全性增强、代码可维护性提高。

2、**Q: 如何在C# MVC中调用存储过程并处理返回结果?

A: 在C# MVC中,可以通过SqlConnectionSqlCommand对象来调用存储过程,需要创建数据库连接,然后创建SqlCommand对象并设置其命令类型为StoredProcedure,添加存储过程的参数并执行命令,通过SqlDataReader读取返回结果并进行处理。

 using (var connection = new SqlConnection(connectionString))
   {
       var command = new SqlCommand("GetUserById", connection);
       command.CommandType = CommandType.StoredProcedure;
       command.Parameters.AddWithValue("@UserId", userId);
       connection.Open();
       using (var reader = command.ExecuteReader())
       {
           if (reader.Read())
           {
               // 处理返回结果
           }
       }
   }