SP Executed Successfully But Data Not Updated - c#

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?

Related

SQL Join Stored Procedure Does Not Return List In Blazor Server

Here I have blazor server app, where I have stored procedure [dbo].[spGetAllChapter] which return list of chapter name, class name and subject name in SSMS.
To call this stored procedure [dbo].[spGetAllChapter] I have used _dbContext.Database.ExecuteSqlRaw().
Now, the problem is that on calling stored procedure it does not return list instead it shows -1 value, but on executing same stored procedure in SSMS returns list.
Below is my stored procedure
ALTER PROCEDURE [dbo].[spGetAllChapter]
AS
BEGIN
SELECT CH.ChapterId
, CH.ChapterName
, SC.ClassName
, S.SubjectName
FROM [dbo].[Chapter] AS CH
JOIN [dbo].[SchoolClass] AS SC
ON CH.SchoolClassId= SC.SchoolClassId
JOIN [dbo].[Subject] AS S
ON CH.SubjectId = S.SubjectId
END
Below is how I have called stored procedure
public eLearningDBContext _dbContext = new eLearningDBContext();
//getChapterList is -1 instead of returning list from procedure
var getChapterList = _dbContext.Database.ExecuteSqlRaw($"EXEC dbo.spGetAllChapter");
The docs for ExecuteSqlRaw say that the function:
Executes the given SQL against the database and returns the number of rows affected.
Note that it doesn't return the data, but the number of rows affected. Perhaps what you're looking for is FromSqlRaw
Alternatively, you don't need a stored procedure to accomplish what you want; you can simply project the columns you want in a regular EF query, like:
_dbContext.Chapters.Select(ch => new
{
ChapterId = ch.ChapterId,
ChapterName = ch.ChapterName,
ClassName = ch.SchoolClass.ClassName,
SubjectName = ch.Subject.SubjectName
}).ToList()
This will give you a list of anonymous objects with the fields you want, but you could also create a named type (Like ChapterAbstract or something) and project to that instead.
If the context was created DB first, you can update the DataModel via the Wizard to include Stored Procedures and Functions. Then you can call the SP directly from the context
_dbcontext.spGetAllChapter();
I some how solved by making this helper class
public static class SQLHelper
{
public static List<T> RawSqlQuery<T>(string query, Func<DbDataReader, T> function)
{
using (var context = new eLearningDBContext())
{
using (var command = context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = query;
command.CommandType = CommandType.Text;
context.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
var entities = new List<T>();
while (result.Read())
{
entities.Add(function(result));
}
return entities;
}
}
}
}
}
var list = SQLHelper.RawSqlQuery($"EXEC dbo.spGetAllChapter",
x => new ChapterVM {
ChapterId = (int)x[0],
ChapterName = (string)x[1],
ClassName = (string)x[2],
SubjectName = (string)x[3]
}).ToList();

Stored procedure not detecting change in database in Blazor server

Here I have a stored procedure dbo.sp_GetChatMessages which returns all columns that is DualMessageId,SenderName,ReceiverName,MessageBody,SendOn,IsSeen column value from table DualMessage.
Now the problem is that if I make any changes to any of the column of DualMessage table and then call the procedure from my service, then the procedure returns same old the value which are before making any changes, that is it does not return that new changed value but running the same procedure in SQL Server Management Studio (SSMS) works fine and gives the changed value.
Below is how I call my procedure in service
public class MainService
{
public BlazorDBContext db = new BlazorDBContext();
public List<DualMessage> GetAllChatMessagesToDisplay(string loggedinUserName)
{
SqlParameter param1 = new SqlParameter("#loggedInUserName", loggedinUserName);
var messagesList = db.DualMessage.FromSqlRaw("EXECUTE dbo.sp_GetChatMessages #loggedInUserName", param1).ToList();
return messagesList;
}
}
Below is stored procedure
ALTER PROCEDURE [dbo].[sp_GetChatMessages] (#loggedInUserName nvarchar(500))
AS
SELECT *
FROM (
SELECT
DualMessageId, SenderName, ReceiverName, MessageBody, SendOn, IsSeen,
ROW_NUMBER() OVER(
PARTITION BY
concat(#loggedInUserName, CASE WHEN senderName =#loggedInUserName
THEN receiverName
ELSE senderName END )
ORDER BY sendOn DESC ) AS rn
FROM DualMessage
WHERE senderName=#loggedInUserName
OR receiverName=#loggedInUserName) as msg
WHERE
msg.rn=1
ORDER BY DualMessageId DESC;

Return id of record when insert or update or delete record

When I insert or update or delete an entity with Dapper, I need to return the id of entity.
I am using this code :
var role = await roleConnection.ExecuteAsync("UPDATE Role SET IsDelete = #isDelete, RoleName = #roleName, SecurityStamp = #securityStamp WHERE Role.Id = #id SELECT SELECT CAST(SCOPE_IDENTITY() AS INT)"
, new
{
isDelete = request.IsDelete = false,
roleName = request.RoleName,
securityStamp = Guid.NewGuid(),
id = request.Id
});
but it does not show me anything.
How can I do this?
Well, in the case of UPDATE or DELETE, you already must have the id, otherwise you couldn't be calling any of these methods - correct?
In the case of an INSERT, if your table is in SQL Server and has an INT IDENTITY column, you can use something like this:
INSERT INTO dbo.YourTable (list-of-columns)
OUTPUT Inserted.Id -- or whatever your IDENTITY column is called
VALUES (list-of-values)
and then from your C# code, use cmd.ExecuteScalar() (or ExecuteScalarAsync, if your prefer) to run this and get back a single, atomic value (the newly created id value):
var result = cmd.ExecuteScalar(....);
if (result != null)
{
int newId = Convert.ToInt32(result);
}

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.

MVC4 and Entity Framework 5 stored procedures

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

Categories