Simple example:
I would create 2 Stored Procedure for the
User
Table, and would load inside the Entity Framework .
Create Table User
CREATE TABLE [dbo].[User](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[UserName] [varchar](50) NULL,
[Password] [varbinary](128) NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Stored Procedure
CREATE PROCEDURE SP_Insert_User
(
@UserName varchar(50),
@Password varchar(30)
)
AS
BEGIN
INSERT INTO [User]([UserName], [Password]) VALUES(@UserName, PWDENCRYPT(@Password));
SELECT [UserId], [UserName], [Password] FROM [User] WHERE [UserId] = @@IDENTITY;
END
CREATE PROCEDURE SP_User_Verify
(
@UserName varchar(50),
@Password varchar(30)
)
AS
BEGIN
SELECT * FROM [User] WHERE [User].[UserName] = @UserName AND
PWDCOMPARE(@Password,[User].[Password]) = 1
END
The SP_Insert_User
to enter new users and SP_User_Verify
to verify the existence of the user with the return of their data.
In your Model, I import both Stored Procedure this way
Choosethetwowiththeirnamesthatinthecontextwillbecreatedtworeturnfunctionsinthisway:
public partial class ObjEntities : DbContext
{
public ObjEntities()
: base("name=ObjEntities") { }
public DbSet<User> User { get; set; }
public virtual ObjectResult<SP_Insert_User_Result> SP_Insert_User(string userName, string password)
{
var userNameParameter = userName != null ?
new ObjectParameter("UserName", userName) :
new ObjectParameter("UserName", typeof(string));
var passwordParameter = password != null ?
new ObjectParameter("Password", password) :
new ObjectParameter("Password", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<SP_Insert_User_Result>("SP_Insert_User", userNameParameter, passwordParameter);
}
public virtual ObjectResult<SP_User_Verify_Result> SP_User_Verify(string userName, string password)
{
var userNameParameter = userName != null ?
new ObjectParameter("UserName", userName) :
new ObjectParameter("UserName", typeof(string));
var passwordParameter = password != null ?
new ObjectParameter("Password", password) :
new ObjectParameter("Password", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<SP_User_Verify_Result>("SP_User_Verify", userNameParameter, passwordParameter);
}
}
How to use:
class Program
{
static void Main(string[] args)
{
using (ObjEntities cx = new ObjEntities())
{
SP_User_Verify_Result user = ValidateUser("USUARIO2", "SENHA2", cx);
}
}
public static SP_User_Verify_Result ValidateUser(string UserName, string Password, ObjEntities cx)
{
return cx.SP_User_Verify(UserName, Password).FirstOrDefault<SP_User_Verify_Result>();
}
}
Debug:
IfinthislineSP_User_Verify_Resultuser=ValidateUser("USUARIO2", "SENHA2", cx);
the variable user
is null
, then the user was not found, consequently, unauthorized user.