How to use stored procedures with SqlParameters in EF Core 3.0 - .net-core-3.0

I have tried the below
var p = new SqlParameter("Option", "AUTHENTICATE");
var user = _context.Set<User>().FromSqlRaw("EXECUTE dbo.spGeneral_Authenticate #Option", p).ToList();
var user = _context.Set<User>().FromSqlRaw("EXECUTE dbo.spGeneral_Authenticate #Option=#Option", p).ToList();
and
SqlParameter[] ps = new SqlParameter[1];
ps[0] = new SqlParameter("Option", "AUTHENTICATE");
var user = _context.Set<User>().FromSqlRaw("EXECUTE dbo.spGeneral_Authenticate #Option", ps).ToList();
var user = _context.Set<User>().FromSqlRaw("EXECUTE dbo.spGeneral_Authenticate #Option=#Option", ps).ToList();
Error:
InvalidCastException: The SqlParameterCollection only accepts non-null
SqlParameter type objects, not SqlParameter objects.

InvalidCastException: The SqlParameterCollection only accepts non-null
SqlParameter type objects, not SqlParameter objects.
For the above error, SqlParameter should be Microsoft.Data.SqlClient.SqlParameter not System.Data.SqlClient.SqlParameter

In .Net core 3.0 or above version,Please use below code:
Instead of System.Data.SqlClient.SqlParameter Use Microsoft.Data.SqlClient.SqlParameter
int AuthourId = 3;
Microsoft.Data.SqlClient.SqlParameter authorId = new Microsoft.Data.SqlClient.SqlParameter("#AuthorId", AuthourId);
IEnumerable<Book> booksByAuthor = shopDbContext.Books
.FromSqlRaw("Select * from Book where AuthorId=#AuthorId", authorId)
.ToList();

Related

Can't figure out how to store outputted parameters to variables using SQL Datasource ASP.Net

I'm working on an application where it requires me to find the username of the user logged in, query against an employee table where the username = active user, and then return EmployeeID, TeamID, and PositionID to set Session State variables to create different views base on each user.
I have created this stored procedure to output the needed parameters.
CREATE PROCEDURE ASP_UserSession #Username nvarchar(256), #UserID int OUTPUT, #TeamID int OUTPUT, #PositionID int OUTPUT
AS
SELECT #UserID = ID, #TeamID = TeamID, #PositionID = PositionID
FROM Employee
WHERE UserName = #Username
Now the issue I'm having is storing the outputed parameters into the code behind file in order set the parameters in Session State.
I'm about ready to pull all of my hair out! Please help!
The DbParameter class has a Direction property, to which you can set a value of ParameterDirection.Output
After executing the stored procedure, get the parameter object from the parameters collection of the command object and get its value.
I was able to fix my issue with this code:
MembershipUser user = Membership.GetUser();
string activeuser = user.UserName;
using (System.Data.SqlClient.SqlConnection sc1 =
new System.Data.SqlClient.SqlConnection(#"Data Source=DRIFT\GANDALF;Initial Catalog=Wizard_Swears;" +
"Integrated Security=True"))
{
sc1.Open();
using (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())
{
command1.CommandType = CommandType.Text;
command1.Connection = sc1;
// DIRECTION :: Input
command1.CommandText = "select #UserID = [ID], #TeamID = [TeamID], #PositionID = [PositionID] FROM [Employee] WHERE ([UserName] = #UserName)";
System.Data.SqlClient.SqlParameter paramter1 = command1.Parameters.Add("#UserName", activeuser);
System.Data.SqlClient.SqlParameter paramter2 = command1.Parameters.Add("#UserID", SqlDbType.SmallInt);
System.Data.SqlClient.SqlParameter paramter3 = command1.Parameters.Add("#TeamID", SqlDbType.SmallInt);
System.Data.SqlClient.SqlParameter paramter4 = command1.Parameters.Add("#PositionID", SqlDbType.SmallInt);
paramter1.Direction = ParameterDirection.Input;
paramter2.Direction = ParameterDirection.Output;
paramter3.Direction = ParameterDirection.Output;
paramter4.Direction = ParameterDirection.Output;
command1.ExecuteNonQuery();
//Store values to variables to be set to session
string userID = paramter2.Value.ToString();
string teamID = paramter3.Value.ToString();
string positionID = paramter4.Value.ToString();
UserIDLBL.Text = userID;
TeamIDLBL.Text = teamID;
PositionIDLBL.Text = positionID;
Session["Username"] = activeuser;
Session["UserID"] = UserIDLBL.Text;
Session["AMID"] = TeamIDLBL.Text;
Session["PositionID"] = PositionIDLBL.Text;

update Binary field in sql server

I have a string which is an encrypted binary value
(0x00C11EA094DC7F45AD2B13F42E26ED03010000006018F6DFCEC8BAFC47AC2854C21A5B00FEFA7C3035A9A4EF7AEBB9FDADBF7FA4B2E6392EA0DC4614).
I need to pass the exact above string to a VarBinary column in SQL Server from .net.
How can I do this?
Regards
Rajeesh
You can use
var input = "your value string";
var connectionString = "";
using(var connection = new SqlConnection(connectionString))
{
connection.Open();
using(var command = new SqlCommand("your query : stored procedure", connection))
{
command.CommandType = CommandType.StoredProcedure;
// your parameter in your stored procedure
SqlParameter parameter = new SqlParameter("#parameter", SqlDbType.VarBinary);
parameter.Direction = ParameterDirection.Input;
parameter.Value = Encoding.ASCII.GetBytes(input);
command.Parameters.Add(parameter);
command.ExecuteNonQuery();
}
}

Exception while saving data in Entity Framework 4.0

Exception :
Unable to update the EntitySet 'Audit_Log' because it has a
DefiningQuery and no element exists in the
element to support the current
operation.
I am using like that
Audit_LogEntity ale = new Audit_LogEntity();`
MemoryStream ms = new MemoryStream();
NetDataContractSerializer serialize = new NetDataContractSerializer();
serialize.Serialize(ms, obj);
Audit_Log al = new Audit_Log();
al.Object = ms.ToArray();
al.DateTime = DateTime.Now;
al.Page_Name = pagename;
al.Pageid = uniqueid;
al.UserId = userid;
ale.AddToAudit_Log(al);
ale.SaveChanges();

How to bind XML data to RadioButtonList using XmlDocument?

I'm stumped here. I've dynamically created RadioButtonLists before using data from a database, but not from XML. I'm not sure if I'm suppose to use the same method, but what I have so far isn't working. Here's what I have (stAddress is the value I'm getting from the user):
XmlDocument xAddress = new XmlDocument();
xAddress.Load("http://myxmlservice/geocode?address=" + stAddress);
XmlNodeList xNodeList = xAddress.DocumentElement.SelectNodes("response");
XmlNode address = xNodeList.Item(0).SelectSingleNode("address");
XmlNode latlong = xNodeList.Item(0).SelectSingleNode("latlng");
rbMultiAdd.DataSource = xNodeList;
rbMultiAdd.DataTextField = address.InnerText;
rbMultiAdd.DataValueField = latlong.InnerText;
rbMultiAdd.DataBind();
I keep getting an error on the DataBind() = "DataBinding: 'System.Xml.XmlElement' does not contain a property with the name '330 S Valley View Blvd'."
330 S Valley View Blvd is one of the results from my XML data.
Is there another way I should be doing this since the data is XML?
Thank you for any assistance.
I figured this out using what #Josh posted as a reference.
XmlNodeList xNodeList = xAddress.DocumentElement.SelectNodes("response");
var addrs = new List<KeyValuePair<string, string>>();
foreach (XmlNode xNode in xNodeList)
{
var xAddr = xNode["address"].InnerText;
var xLatLng = xNode["latlng"].InnerText;
addrs.Add(new KeyValuePair<string, string>(xAddr, xLatLng));
}
rbMultiAdd.DataSource = addrs;
rbMultiAdd.DataTextField = "Key";
rbMultiAdd.DataValueField = "Value";
rbMultiAdd.DataBind();
//Thanks Psykopup
// Above code works fine for me when I Put "attributes"
string strSP = "USP_XML_StoredProcedure";
cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = strSP;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Id", DbType.Int32).Value = 28;
XmlReader reader = cmd.ExecuteXmlReader();
if (reader.Read())
{
xdoc.Load(reader);
}
XmlNodeList xNodeList = xdoc.SelectNodes("/Parent/REC");
var source = new List<KeyValuePair<string, string>>();
foreach (XmlNode xNode in xNodeList)
{
var xCode = ***xNode.Attributes***["ID"].InnerText;
var xText = ***xNode.Attributes***["Name"].InnerText;
source.Add(new KeyValuePair<string, string>(xCode, xText));
}
rbListDistrict.DataSource = source;
rbListDistrict.DataTextField = "Value";
rbListDistrict.DataValueField = "Key";
rbListDistrict.DataBind();
DataTextField and DataValueField both refer to property names on your object. Data binding uses reflection to look those up on the item that is being bound to.
In this case it is a XmlNode type. Which, as the error states doesn't have a property of type "330 S Valley View Blvd", which is the value of InnerText.
In this case you are probably going to have to project your list onto an intermediate type and use that for binding. There are many different ways to do this, here is one:
XmlNodeList xNodeList = xAddress.DocumentElement.SelectNodes("response");
var addresses = xNodeList.Select(n => new KeyValuePair<String, String>(
n.SelectSingleNode("address"), n.SelectSingleNode("latlng")))
.ToList();
rbMultiAdd.DataSource = addresses;
rbMultiAdd.DataTextField = "Key";
rbMultiAdd.DataValueField = "Value";
rbMultiAdd.DataBind();

Returning Dataset using DBFactory and Oracle Stored Procedure sys ref cusror

I'm trying to return dataset from oracle ref cursor using ODP.NET provider and DBFactory.
I'm getting following error when i call this function:
Invalid parameter binding
Parameter name: io_cursor
code:
Dim dbManager As DBManager = New DBManager(ORACONN)
Dim ds As New DataSet()
Dim cmd As DbCommand = dbManager.CreateCommand()
cmd.CommandText = "SP_NAME"
Dim param As DbParameter = cmd.CreateParameter()
param.ParameterName = "io_cursor"
param.Value = Nothing
param.DbType = DbType.Object
param.Direction = ParameterDirection.Output
cmd.Parameters.Add(param)
Dim da = dbManager.CreateDataAdaptor()
da.SelectCommand = cmd
da.Fill(ds)
Return ds
What am i missing here? Will DbType.Object work for OracleDbType.RefCursor type?
I don't think using DbType.Object will work. I think you should be using OracleDbType.RefCursor instead.
Documentation and example (C#)

Resources