MVC4 and Entity Framework 5 stored procedures - c#

Hi Im trying to access a database table in my mvc4 application using a stored procedure and Entity Framework 5.
I created a FormValueModel.edmx file and imported the User Table and the GetUser Stored Procedure
Here is the code for the GetUser Stored Procedure
SELECT
*
FROM
[User].[User]
Where
#UserName = UserName
AND #UserPassword = UserPassword
AND Active = 1
Here is the code in my Controller to access the stored procedure
using (var db = new FormValueEntities())
{
string userName ="TestUser"
string password = "Password"
var query = db.GetUser(userName, password);
}
Why cant I access the table by using query.UserName or query.UserPassword ect.
Thanks in advance

You need to take the first item from the query i.e.
var user = db.GetUser(userName, password).SingleOrDefault();

you need to do something like this:
var query = (from a in db.GetUser(userName, password)
select new User
{
UserName =a.UserName
...other fields
}).tolist();

Check the Stored Procedure!!!
SELECT
*
FROM
[User].[User]
Where
#UserName = UserName
AND #UserPassword = UserPassword
AND Active = 1
Good:
SELECT
*
FROM
[User].[User]
Where
UserName = #UserName
AND UserPassword = #UserPassword
AND Active = 1

Related

Passing tablename to a stored procedure c#

I'm new to programming and I'm programming with Visual Studio. I'm trying to get an input from user (a name of a site like google.com) and search for the site name toward my tables (I have different domain tables such as .com , .org , etc).
So, I'm trying to write this stored procedure which selects from a table without actual table name (I'm trying to pass table name from input to stored procedure) here is my stored procedure:
CREATE PROCEDURE test
#link nvarchar(50)
AS
SELECT *
FROM #link
I have defined linksg (set and get) like this:
public string linksg
{
get { return link; }
set { link = value; }
}
and this is how I defined linksg in a function (my search_sitedomain function takes a domain like .com and gives a link to a table which includes your sitename like .com table):
public void search_sitedomain()
{
SqlConnection con = new SqlConnection("Data Source=SM;Initial Catalog=mohandesi-net;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand("search_sitedomain", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#domain", domain);
con.Open();
string link = Convert.ToString(cmd.ExecuteScalar());
linksg = link;
MessageBox.Show(link);
}
The search_sitedomain function works perfectly fine and returns the link but my stored procedure doesn't work like it can't replace #link with a tablename (like .com)
So what am I doing wrong?
In my opinion having a parametrized table name is a huge security hole, but it's possible to do it as follows:
CREATE PROCEDURE test
#link nvarchar(50)
AS
EXEC ('SELECT * FROM dbo.['+#link+']');

SP Executed Successfully But Data Not Updated

I am using Telerik Open Access for interaction with MSSQL SERVER 2012.
I have made a stored procedure which will set IsActive column of Role Table to 0(false) and return all data of Role where IsActive= 1 (True)
My Role table has columns:
RoleId(int), RoleName(varchar(50)), AliasName(varchar(50)), IsActive(bit).
My Stored Procedure:
ALTER PROCEDURE [SPDeleteRole]
#Role_Id int
AS
BEGIN
UPDATE [Role] SET IsActive = 0 WHERE RoleId = #Role_Id
Select * from [Role] WHERE IsActive = 1 ORDER BY RoleName
END
I call this SP in my application like below:
public List<RoleDTO> DeleteRole(int roleId)
{
OAParameter oaParameter = new OAParameter();
oaParameter.ParameterName = "Role_Id";
oaParameter.DbType = System.Data.DbType.Int32;
oaParameter.Value = roleId;
List<RoleDTO> roleList = base.ExecWithStoreProcedureGetDataWithParam("SPDeleteRole", oaParameter);
return AutoMapper.Mapper.Map<List<RoleDTO>>(roleList);
}
public List<T> ExecWithStoreProcedureGetDataWithParam(string query, OAParameter parameters)
{
var queryResult = dbContext.ExecuteQuery<T>(query, CommandType.StoredProcedure, parameters);
dbContext.Dispose();
return queryResult.ToList();
}
Now my problem is this works fine. But when I refresh the page, the role which I inactivated comes to in the list.
I checked through debugging that list comes from SP is exactly of Active Roles. But as soon as I refresh the page the role inactivated roles comes again in the list. I have verified SP by executing it in MSSQL SERVER and it works fine.
Issue:
May be you should write dbContext.SaveChanges() before you dispose the dbcontext?

get list from table using stored procedure entity framework

I am using same stored procedure for inserting and fetching data on condition base.
Stored Procedure-
ALTER PROCEDURE dbo.sp_SaveUserRole
#company_name nvarchar(50)=null,
#address nvarchar(250)=null,
#mobileno int =0,
#phoneno int=0,
#faxno int=0,
#email nvarchar(250)=null,
#regno int=0,
#establish_date datetime=null,
#cond int=0
AS
if(#cond=1)
begin
insert into Company (company_name,address,mobileno,phoneno,faxno,regno,email,establish_date) values (#company_name,#address,#mobileno,#phoneno,#faxno,#regno,#email,#establish_date)
end
else if(#cond=2)
begin
select * from company where isactive = 'True';
end
RETURN
As on inserting data using entity framework I am doing this-
public ActionResult SaveRole(CompanyModel cmp)
{
var company_name = cmp.Company_Name;
var regno = cmp.regNo;
var mobileno = cmp.mobileNo;
var phoneno = cmp.phoneNo;
var establish_date = cmp.establish_Date;
var email = cmp.emaiL;
var address = cmp.Address;
var faxno = cmp.faxNo;
db.sp_SaveUserRole(company_name, address, mobileno, phoneno, faxno, email, regno, establish_date,1);
return Json(new { success = true });
Note-
Here condition is 1 so it goes to insert data procedure.
Trying to get a list-
var list = db.sp_SaveUserRole("", "", 0, 0, 0, "", 0, null, 2).ToList();
I tried this way of getting data from table, where I had to pass necessary arguments to this procedure call. Though I wanted to go this procedure only to 2nd condition I've mentioned there.
So only for this 2nd condition How can I modify this procedure without passing arguments?
Instead of using a stored procedure I would add your company table as an entity in your edmx and access it in code.
That way instead of passing #Cont=2 to a stored proc you can instead use LINQ to access the data you require as the SQL seems very basic.
You can then remove that piece of SQL from your stored proc as mixing Inserts with selects doesnt feel right.
e.g.
// For insert
if (cont == 1)
{
// Call your stored proc here
// or if you add the company table to EF you can use the Insert use the Add
// e.g. Rough Example
_yourEntities.Companies.Add(cmp);
// Update the DB
_yourEntities.SaveChanges();
}
else
{
var companies = _yourEntities.Companies.Where(c => c.isactive == 'True');
}
If this solution is not an option i would still look to split the stored procs into two to make life easily.
Ideally though as you using Entity Framework and are looking to insert and select from a single table you get this functionality for free when you add the Company table as a entity in EF.

Trying to Select TimeTickets from Database for just the user that created them

I have a small project on the go where a user can log in, create a TimeTicket and then view the TimeTicket.
When I go to view TimeTickets I can see all TimeTickets in the database.
I only want the user to be able to see the TimeTickets that him/her created.
I was thinking a simple query should work such as:
"SELECT * FROM M_TimeTickets WHERE EmployeeID = CurrentUserName";
All my TimeTickets are stored in a M_TimeTickets table.
All my User Info is stored in my UserProfile table.
In my UserProfile table I have 3 columns. (Email, UserId, EmployeeID).
I would like to Select all TimeTickets that are equal to EmployeeID.
Set this line:
var selectCommand = ("SELECT * FROM M_TimeTickets WHERE EmployeeID = {0}", WebSecurity.CurrentUserId);
To this:
var selectCommand = string.Format("SELECT * FROM M_TimeTickets WHERE EmployeeID = '{0}'", WebSecurity.CurrentUserId);

How to write update stored procedure in webmatrix form?

Here I write update query in my webmatrix form which run correctly but I want to use a stored procedure in place of query so how can I write that?
var UpdateQuery = "UPDATE Reg_tb SET FirstName = #0, LastName = #1, UserName = #2, Password = #3 WHERE UID = #4";
db.Execute(UpdateQuery, FirstName, LastName, UserName, Password, Userid);
Maybe this?
var execProc="EXEC ProcName FirstName=#0,LastName=#1,UserName=#2,Password=#3, UID=#4";
db.Execute(execProc,FirstName,LastName,UserName,Password,Userid);

Categories