在SQL 2008 Query中我只执行,如果成功则返回1。现在我如何在MVC 5 EF dbcontext中执行此操作?
usp_CreateNewAccount usernamehere, passwordhere, emailhere
我使用Entity Framework创建了我的Controller项,并编辑了控制器Create方法。
db.Users.Add(user);
db.Users.SqlQuery("usp_CreateNewAccount fsdfsdf, sdfsdfsd, dasda");
db.SaveChanges();
它没有结果。我无法创建用户。任何可能的解决方案?
答案 0 :(得分:1)
假设您有存储过程usp_CreateNewAccount
:
CREATE PROCEDURE usp_CreateNewAccount
@usernamehere NVARCHAR(...),
@passwordhere NVARCHAR(...),
@emailhere NVARCHAR(...)
AS
BEGIN
-- insert query here
END
然后你可以使用DbContext.Database.SqlQuery
这样的参数:
using (var db = new DataContext()) // DataContext is your DBContext name
{
var userName = new SqlParameter()
{
ParameterName = "usernamehere",
DbType = DbType.String,
Value = "fsdfsdf"
};
var password = new SqlParameter()
{
ParameterName = "passwordhere",
DbType = DbType.String,
Value = "sdfsdfsd"
};
var email = new SqlParameter()
{
ParameterName = "emailhere",
DbType = DbType.String,
Value = "dasda"
};
// suppose "User" table exists with "db.Users" as DbSet<User> collection
db.Database.SqlQuery<User>("EXEC usp_CreateNewAccount {0}, {1}, {2}", new Object[] { userName, password, email });
}
由于插入和保存操作已由存储过程查询处理,因此没有理由在此使用db.Users.Add
和db.SaveChanges
方法。