How to use Store procedure in entity frame work - entity-framework

I have created store procedure in Sql server its working.when i imliment it into my entity framework, its throws exception, I am new to this, kindly suggest
//SQL//
create procedure sp_getUserID
#deviceID int,
#userID int out
as
Begin
Select #userID= userId from UserTable
where deviceID = #deviceID
End
// C#
var UserID =0;
// This line error ERROR: //The specified parameter name '#userID' is not valid.
System.Data.Entity.Core.Objects.ObjectParameter UserOutput = new System.Data.Entity.Core.Objects.ObjectParameter("#userID", typeof(int));
var objStoredProcd = dbContext.sp_getUserID(UserOutput, UserLogin.DeviceUUID);
UserID = Convert.ToInt32(UserOutput.Value);

Related

how to call stored procedure with parameter in entity framework

I am getting below error when I am calling procedure from entity framework with parameter
alter proc GetResultsForCampaign
#aa int
as
begin
SELECT aa from xyz
end
calling code
var result = context.Database.SqlQuery("GetResultsForCampaign #aa", 22).ToList();
error must declare the variable #aa
You can try this.
using Microsoft.Data.SqlClient;
var result = await db.Context
.FromSqlRaw("exec [dbo].[your_sp] #param1, #param2",
new SqlParameter("param1", value1),
new SqlParameter("param2", value2))
.AsNoTracking() // optional
.ToListAsync()

insert data using labmda expression

I have a insert sp
create procedure sp_insert_services
#Service_Type nvarchar(50),
#Frequency nvarchar(50),
as
insert INTO tbl_fl_Master_List
(Service_Type,Frequency)
values
(#Service_Type,
#Frequency)
now how i write this through lambda expression,linq to sql and EF?
i tried this but this show error
var insert = insertt.tbl_fl_Master_List();
if(insertt!=null)
{
insertt.tbl_fl_Master_List.Add();
}
insertt.SaveChanges();
Error 8 Non-invocable member 'chart_project.Track_Data.tbl_fl_Master_List' cannot be used like a method.
Error 9 No overload for method 'Add' takes 0 arguments
and also i try this
public static string Insert_master_services(string Service_Type,string Frequency)
{
Data insertt=new Data();
tbl_fl_Master_List t = new tbl_fl_Master_List();
t.Service_Type = Service_Type;
t.Frequency = Frequency;
insertt.SaveChanges();
}

Call stored procedure in EF 6 Repository Pattern without output parameters

I'm working with Repository Pattern and EF6. What I need to do is to call a SP that delete records for mapping table that have nothing in common within the repository I'm calling the SP.
I've tried with
this.dbSet.SqlQuery("exec mySP #Param1, #Param2", param1, param2);
but this returns all the records from the DB of the current repository I'm in. It's like I've wrote "SELECT * FROM Group" (if I'm in GroupRepository).
My SP returns nothing since it's deleting some records and I already wasted 2 days of searching how to call the SP. I can give additional info if needed.
Can anybody help?
Finally I manage to execute my stored procedure, which was accepting a List<int> and an Id. The code looks like this:
SQL SERVER:
CREATE TYPE [dbo].[IntListType] AS TABLE
(
[Item] INT
);
GO
CREATE PROCEDURE [removeEventUsersFromEvents]
(
#EventIds [dbo].[IntListType] READONLY,
#UserId INT
)
AS
BEGIN
BEGIN Tran T1
DECLARE #query NVARCHAR(MAX)
SET NOCOUNT ON;
SET #query = 'DELETE FROM [EventUser]
WHERE [EventID] IN (SELECT Item from #EventIds) AND [UserID] = #UserId';
EXECUTE sp_executesql #query,
N'#EventIds [dbo].[IntListType] READONLY, #UserId INT',
#EventIds,
#UserId;
COMMIT Tran T1
END;
C#:
List<int> eventIdsToBeDeleted = this.dbSet...(geting some Ids from the db);
DataTable dt = new DataTable("IntListType");
dt.Columns.Add("Item", typeof(Int32));
eventIdsToBeDeleted.ForEach(id => dt.Rows.Add(id));
var eventIds = new SqlParameter("EventIds", SqlDbType.Structured);
eventIds.TypeName = "dbo.IntListType";
eventIds.Value = dt;
foreach (var user in usersToBeDeletedFromEvents)
{
var userId = new SqlParameter("UserId", SqlDbType.Int);
userId.Value = user.UserID;
this.Context.Database.SqlQuery(typeof(List<int>),
"EXEC removeCalendarEventUsersFromSpecificGroupAndEvents
#CalendarEventIds,
#UserProfileDetailId",
eventIds,
userId);
}
This will eventually return an empty List<int>.

EntityFrameWork and TableValued Parameter

I'm trying to call a stored procedure from EntityFramework which uses Table-value parameter.
But when I try to do function import I keep getting a warning message saying -
The function 'InsertPerson' has a parameter 'InsertPerson_TVP' at
parameter index 0 that has a data type 'table type' which is currently
not supported for the target .NET Framework version. The function was
excluded.
I did a initial search here and found few posts which says It's possible in EntityFrameWork with some work arounds and few saying it's not supported in current versions.
Does any one know a better approach or solution for this problem?
I ended up doing this, Please note we are working on EF DataContext(not ObjectContext)
Executing a Stored procedure with output parameter
using (DataContext context = new DataContext())
{
////Create table value parameter
DataTable dt = new DataTable();
dt.Columns.Add("Displayname");
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("TimeStamp");
DataRow dr = dt.NewRow();
dr["Displayname"] = "DisplayName";
dr["FirstName"] = "FirstName";
dr["LastName"] ="LastName";
dr["TimeStamp"] = "TimeStamp";
dt.Rows.Add(dr);
////Use DbType.Structured for TVP
var userdetails = new SqlParameter("UserDetails", SqlDbType.Structured);
userdetails.Value = dt;
userdetails.TypeName = "UserType";
////Parameter for SP output
var result = new SqlParameter("ResultList", SqlDbType.NVarChar, 4000);
result.Direction = ParameterDirection.Output;
context.Database.ExecuteSqlCommand("EXEC UserImport #UserDetails, #ResultList OUTPUT", userdetails, result);
return result == null ? string.Empty : result.Value.ToString();
}
My Table-Value-Parameter (UDT Table) script looks like this:
CREATE TYPE [dbo].[UserType] AS TABLE (
[DisplayName] NVARCHAR (256) NULL,
[FirstName] NVARCHAR (256) NULL,
[LastName] NVARCHAR (256) NULL,
[TimeStamp] DATETIME NULL
)
And my store procedure begins like
CREATE PROCEDURE UserImport
-- Add the parameters for the stored procedure here
#UserDetails UserType Readonly,
#ResultList NVARCHAR(MAX) output
AS
For Stored procedure without output parameter we don't need any ouput parameter added/passed to SP.
Hope it helps some one.
Perhaps we could also consider the SqlQuery method:
[Invoke]
public SomeResultType GetResult(List<int> someIdList)
{
var idTbl = new DataTable();
idTbl.Columns.Add("Some_ID");
someIdList.ForEach(id => idTbl.Rows.Add(id));
var idParam = new SqlParamter("SomeParamName", SqlDbType.Structured);
idParam.TypeName = "SomeTBVType";
idParam.Value = idTbl;
// Return type will be IEnumerable<T>
var result = DbContext.Database.SqlQuery<SomeResultType>("EXEC SomeSPName, #SomeParamName", idParam);
// We can enumerate the result...
var enu = result.GetEnumerator();
if (!enu.MoveNext()) return null;
return enu.Current;
}
var detailTbl = new DataTable();
detailTbl.Columns.Add("DetailID");
detailTbl.Columns.Add("Qty");
txnDetails.ForEach(detail => detailTbl.Rows.Add(detail.DetailID, detail.Qty));
var userIdParam = new System.Data.SqlClient.SqlParameter("#UserID", SqlDbType.Int);
userIdParam.Value = 1;
var detailParam = new System.Data.SqlClient.SqlParameter("#Details", SqlDbType.Structured);
detailParam.TypeName = "DetailUpdate";
detailParam.Value = detailTbl;
var txnTypeParam = new System.Data.SqlClient.SqlParameter("#TransactionType", SqlDbType.VarChar);
txnTypeParam.Value = txnType;
var result = await db.Database.ExecuteSqlCommandAsync("MySP #UserID, #Details, #TransactionType", userIdParam, detailParam, txnTypeParam);
if(result >= 0)
return StatusCode(HttpStatusCode.OK);
else
return StatusCode(HttpStatusCode.InternalServerError);

Getting return value from the stored procedure

I have written a procedure as following:
ALTER PROC ReturnProc
AS
BEGIN
RETURN 5
END
I am trying to get the return value from the Procedure in the following way:
com.CommandText = "ReturnProc";
com.CommandType = CommandType.StoredProcedure;
SqlParameter parameterReturnValue = new SqlParameter();
parameterReturnValue.Direction = ParameterDirection.ReturnValue;
com.Parameters.Add(parameterReturnValue);
con.Open();
tran = con.BeginTransaction();
com.Transaction = tran;
com.ExecuteNonQuery();
tran.Commit();
//Get the return value
iReturn = Convert.ToInt64(parameterReturnValue.Value);
I failed to get the return value after execution. In the real scenario, I am concatenating the parameters with the procedure, rather than adding them in SqlParameter list.
Could anybody help me on this?
I think you have to retrieve the value from the Parameters collection. See How can I get Stored Procedure return value in C#?