How do I call a stored procedure from NHibernate that has a result using C#? - c#-3.0

I have a stored procedure that loads data and returns on record in a string format. How do I call it and capture the result using NHibernate
Eg below
var query = session.CreateSQLQuery("EXECUTE LoadData #ActualsDate =:ActualsDate, ActualBroadcastMonth =:ActualsMonth")
.SetTimeout(0)
.SetParameter("ActualsDate", actualsDate)
.SetParameter("ActualsMonth", actualsMonth)
.???;
return ...;```

Got the answer
.SetTimeout(0)
.SetParameter("ActualsDate", actualsDate)
.SetParameter("ActualsMonth", actualsMonth)
.UniqueResult;
return query.ToString();

Related

Linq2db.EntityFrameworkCore against Oracle

I don't understand why linq2db is not generating the correct SQL string for this query against Oracle, and it is working perfectly against SQLServer.
string idUser="U1";
await context.Users.ToLinqToDbTable().Where(u=>u.IdUser == idUser).FirstOrDefaultAsyncLinqToDB();
Always returns null. However, it works if el value used directly:
await context.Users.ToLinqToDbTable().Where(u=>u.IdUser == "U1").FirstOrDefaultAsyncLinqToDB();
Looking at the logs, el SQL statement generated is like this:
-- Oracle Oracle11
DECLARE #idUser Varchar2(8) -- String
SET #idUser = 'U1'
SELECT
u.IdUser,
etc..
FROM
USERS u
WHERE
u.IDUSER = :idUser
Why is it generating T-SQL code and not Oracle code (the context is initialized with .UseOracle())?
Thanks

Entity Framework Core, Stored Procedure

I am totally confused regarding how to use Stored Procedures using Entity Framework Core. If the stored procedure return an anonymous type, how do I retrieve the data? If the return type is not anonymous, what should I do? How do I add input/output parameters?
I am asking these questions because everywhere I look, I get a different answer. I guess EF Core is evolving rapidly and Microsoft is dabbling with a lot of ideas.
How do I add input/output parameters?
I'm going to answer this particular question of yours.
Below is a TSQL stored procedure with two input and two output parameters
CREATE PROCEDURE [dbo].[yourstoredprocedure]
-- Add the parameters for the stored procedure here
#varone bigint
,#vartwo Date
,#varthree double precision OUTPUT
,#varfour bigint OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- YOUR CODE HERE
SET #varthree = 10.02;
SET #varfour = #varone;
return;
END
Now To execute this stored procedure using Entity Framework Core
MyContext.Database
.ExecuteSqlCommand(#"EXECUTE [yourstoredprocedure] " +
" {0} " +
", {1} " +
",#varthree OUTPUT " +
", #varfour OUTPUT ", dataOne, dataTwo, outputVarOne, outputVarTwo);
var outputResultOne= outputVarOne.Value as double?;
var outputResultTwo= outputVarTwo.Value as long?;
You can pass your input simply using parameterized query as above. You can also create named parameters. such as for output parameters, I've created two named parameters as -
var outputVarOne = new SqlParameter
{
ParameterName = "#varthree ",
DbType = System.Data.DbType.Double,
Direction = System.Data.ParameterDirection.Output
};
var outputVarTwo = new SqlParameter
{
ParameterName = "#varfour ",
DbType = System.Data.DbType.Int64,
Direction = System.Data.ParameterDirection.Output
};
And This is how using EF Core you execute a stored procedure with input and output parameters. Hope this helps someone.
This solution provides methods that call a stored procedure and maps the returned value to a defined (non-model) entity. https://github.com/verdie-g/StoredProcedureDotNetCore
Microsoft address this issue:
"SQL queries can only be used to return entity types that are part of your model. There is an enhancement on our backlog to enable returning ad-hoc types from raw SQL queries." https://learn.microsoft.com/en-us/ef/core/querying/raw-sql
And here is the issue tracked in GitHub: https://github.com/aspnet/EntityFramework/issues/1862
you might use an extention like StoredProcedureEFCore
Then the usage is more intuitively.
List rows = null;
ctx.LoadStoredProc("dbo.ListAll")
.AddParam("limit", 300L)
.AddParam("limitOut", out IOutParam<long> limitOut)
.Exec(r => rows = r.ToList<Model>());
long limitOutValue = limitOut.Value;
ctx.LoadStoredProc("dbo.ReturnBoolean")
.AddParam("boolean_to_return", true)
.ReturnValue(out IOutParam<bool> retParam)
.ExecNonQuery();
bool b = retParam.Value;
ctx.LoadStoredProc("dbo.ListAll")
.AddParam("limit", 1L)
.ExecScalar(out long l);

Getting "The SqlParameter is already contained by another SqlParameterCollection." error while using SqlQuery command

I am trying to parameterize a dynamic query and run it using SqlQuery method in Entity Framework code first.
The first time I execute SqlQuery it works as expected so I am sure there is nothing wrong with query or parameters but immediately I execute the same command with the same parameters second time and I get this error
"The SqlParameter is already contained by another SqlParameterCollection."
Since I am already using ToList() method here, I have no idea what the cause could be!
Here is the simulated code.
using (var context = Common.GetDbContext())
{
var parameters = new List<SqlParameter>();
//populating parameters here...
var sqlQuery = "Select * from MyTable where UserId=#p1 and And Active=#p2";
// first time
var result = context.Database.SqlQuery<ResultType>(sqlQuery, parameters.ToArray()).ToList();
//second time
result = context.Database.SqlQuery<ResultType>(sqlQuery, parameters.ToArray()).ToList();
}
Any idea?
Hi SqlParameter is clonable. Try this:
result = context.Database.SqlQuery<ResultType>(sqlQuery, parameters.Select(x => x.Clone()).ToArray()).ToList();
See https://msdn.microsoft.com/en-us/library/vstudio/bb338957%28v=vs.100%29.aspx

split values of couch db result

I want to split the values selected from couch db in gwt according to a particular id. I tried to use the String tokenizer but couldn't found something useful. the result returned from couch db is in the following format:
{"_id":"2","_rev":"1-717f76046030a683687ace9ac8f7bdbf","course":"jbdgjbj","passwd":"rty","phone":"24125514444","clgnme":"bjfbjf","address":"jbjfbjb","name":"meenal","cpasswd":"rty","user":"2","fname":"jfbg"}
I just want to get the values and set them in textboxes.
how to do it?
try this ...
Session studentDbSession = new Session("localhost",5984);
Database studentCouchDb = studentDbSession.getDatabase("student");
System.out.println("select");
Document d = studentCouchDb.getDocument(input);
if(d.containsKey("FirstName")){
fname=d.getString("FirstName");//fname is variable
}
if(d.containsKey("LastName")){
lname=d.getString("LastName");//lname is variable
}
if(d.containsKey("Address")){
add= d.getString("Address");//add name is variable
}
finally concatenate all strings and return to client...
all=fname+" "+lname+" "+add;
return all;
This looks like JSON. You can parse it using JSONObject:
JSONObject obj = new JSONObject(yourString);
String course = obj.getString("course");

Use stored procedure in EF(MVC4)

I have a storedprocedure "SelectKP" (Datetime bt,Datetime et), please help to create a class and a repository for this procedure.
Look at this link:
How to execute a stored procedure within C# program
There is not a function generated manually, but it executes stored procedure
Here is simple example.
using (var db = new ModelEntities())
{
var query = db.ExecuteStoreQuery<ModelClass>("StoreProcedureName '" + UserId +"'");
}