EF调用存储过程实例

创建实体:
 1  public class User
 2 {
 3 public string UserID { get; set; }
 4 public string UserName { get; set; }
 5 public string Password { get; set; }
 6 [Description("测试")]
 7 public string UserGroupId { get; set; }
 8 public UserGroup UserGroup { get; set; }
 9 public List<Role> Roles { get; set; }
10 }
11  
12 public class UserGroup
13 {
14 public string GroupID { get; set; }
15 public string GroupName { get; set; }
16 public List<User> Users { get; set; }
17 }
18  
19 public class Role
20 {
21 public string RoleID { get; set; }
22 public string RoleName { get; set; }
23 public List<User> Users { get; set; }
24 }

 

2.2、准备SQL数据
--新增数据
 1 alter PROC createData
 2 @rowNum INT
 3 AS
 4 DECLARE @index INT =1,@id VARCHAR(50)=NEWID()
 5 INSERT dbo.UserGroups
 6 ( GroupID, GroupName )
 7 VALUES ( @id, -- GroupID - nvarchar(128)
 8 N'开发组' -- GroupName - nvarchar(max)
 9 )
10 WHILE(@index<=@rowNum)
11 BEGIN
12 INSERT dbo.Users
13 ( UserID ,
14 UserName ,
15 Password ,
16 UserGroupId
17 )
18 VALUES ( NEWID(),
19 N'张三' , -- UserName - nvarchar(max)
20 N'123456' , -- Password - nvarchar(max)
21 @id -- UserGroupId - nvarchar(128)
22 )
23 SET @index=@index+1
24 END
--删除数据
alter PROC DeleteData
AS
BEGIN
TRUNCATE TABLE dbo.Users
END
--修改数据
ALTER PROC ModifyData
@uid VARchar(50),
@userName varchar(50)
AS
BEGIN
UPDATE dbo.Users SET UserName=@userName WHERE UserID=@uid
END
--查找数据
ALTER PROC GetLlist
@rowNumber int
AS
BEGIN
SELECT * FROM ( SELECT ROW_NUMBER() OVER(ORDER BY UserID) AS ID,* FROM dbo.Users ) AS A WHERE A.ID<=@rowNumber
END
 
2.3C#代码调用实例
2.3.1 查询列表
1 var db = new TestDbContext();
2 SqlParameter[] parameter = new SqlParameter[1];
3 parameter[0] = new SqlParameter("@rowNumber", 10);
4 var users = db.Users.SqlQuery("exec GetLlist @rowNumber", parameter).ToList();
2.3.2  返回有参数的存储过程
 var db = new TestDbContext();
int count = db.Database.SqlQuery(typeof(int),"exec ProSelectCount").Cast<int>().FirstOrDefault();
 
2.3.3  增删查改
 
var db = new TestDbContext();
SqlParameter[] parameter = new SqlParameter[1];
parameter[0] = new SqlParameter("@rowNum", 5);
db.Database.ExecuteSqlCommand("exec CreateData @rowNum", parameter);
 

 

 
 
 
 
posted @ 2015-08-31 11:17  虔城墨客  阅读(421)  评论(0编辑  收藏  举报