如何在C#创建存储过程,然后保存到SQL Server?
技术问答
325 人阅读
|
0 人回复
|
2023-09-14
|
我在这堵墙上撞了一会儿。我知道你可以用。C#代码可以创建一个存储过程。但我不知道的是,我可以把存储过程 保存 到SQL, E: Z0 V+ T" H1 T. X1 g
Server上 ,但可以通过C#代码完成了吗?
0 K+ d& U+ D- F场景是:我想通过代码创建一个测试数据库,然后添加到新的测试数据库(服务器端)-同样,所有操作都是通过相同的方式进行的C#完成代码项目。1 `5 |8 S" V( z, X" U8 A
: s. P6 Z3 y5 p' B# w& C+ z# l# P* t3 g 解决方案: t6 t( q7 g# H5 n; F% `, c7 I2 K8 P
是的,这是可能的。在这里,我给你举个例子。
$ ^/ Y* B4 w" |+ z# f9 upublic partial class InitialEntities : DbMigration { public override void Up() { CreateStoredProcedure( "dbo.InsertEmployee", p => new Code = p.String()Name = p.String()DepartmentId = p.Int(), }body: @"INSERT [dbo].[EmployeeMasters]([Code],[Name],[DepartmentId]) VALUES (@Code,@Name,@DepartmentId) DECLARE @EmployeeId int SELECT @EmployeeId = [EmployeeId] FROM [dbo].[EmployeeMasters] WHERE @@ROWCOUNT > 0 AND [EmployeeId] = scope_identity() SELECT t0.[EmployeeId] FROM [dbo].[EmployeeMasters] AS t WHERE @@ROWCOUNT > 0 AND t0.[EmployeeId] = @EmployeeId" ); CreateStoredProcedure( "dbo.UpdateEmployee", p => new EmployeeId = p.Int()Code = p.String()Name = p.String()DepartmentId = p.Int(), }body: @"UPDATE [dbo].[EmployeeMasters] SET [Code] = @Code,[Name] = @Name,[DepartmentId] = @DepartmentId WHERE ([EmployeeId] = @EmployeeId)" )CreateStoredProcedure( "dbo.DeleteEmployee", p => new EmployeeId = p.Int(), }body: @"DELETE [dbo].[EmployeeMasters] WHERE ([EmployeeId] = @EmployeeId)" );}public override void Down() { DropStoredProcedure("dbo.DeleteEmployee"); DropStoredProcedure("dbo.UpdateEmployee"); DropStoredProcedure("dbo.InsertEmployee"); } }没有实体框架
5 Z( _7 F+ y2 L \; Y/ ^5 E3 I connection)) connection.Open(); cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); connection.Close(); connection)) { connection.Open(); cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); connection.Close(); } } |
|
|
|
|
|