How do I use Entity Framework instead of Ado.net for stored procedure? - entity-framework

I am using a stored procedure in my SQL Server database to take input of the data through the datatable. As I am using ASP.NET MVC now, I want to use Entity Framework instead of ado.net
public void BulkUpload(DataTable dt)
{
dt.TableName = "MainTable";
DataSet dataset = new DataSet();
DataTable dataTable = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
conn.Open();
{
SqlCommand cmd = new SqlCommand("DatatableToDataBase", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mode", SqlDbType.VarChar).Value = "MainTB";
cmd.Parameters.AddWithValue("#Details", SqlDbType.VarChar).Value = dt;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
catch (Exception)
{ }
}

It's very easy just add an entity datamodel to your program
connect to you model :
"entitymodel" context = this.CurrentDataSource;
And pass the stored procedure where you like .
Thats everything
Example:
[WebGet]
public List<callersW> GetCaller()
{
testCDREntities1 context = this.CurrentDataSource;
//sql parameters here
List<callersW> result = context.Database.SqlQuery<callersW>("StoredProcedure").ToList();
return result;
}

Related

ADO.NET add SQLParameters

I am trying to execute a stored procedure with parameters using ADO.NET in .NET Core.
When I try and pass in a SqlParameter object I get the below error.
I have a using statement at the top for System.Data.SqlClient.
Is there another way or new ways of passing Sql parameters to a stored procedure?
public async Task<List<SynchStockDto>> GetStockForSync(int locationBinId, DateTime lastSyncDate)
{
await EnsureConnectionOpenAsync();
var command = GetConnection().CreateCommand();
command.CommandText = "sp_GetStockForSync #LocationBinId, #LastSyncDate";
command.CommandType = CommandType.StoredProcedure;
command.Transaction = GetActiveTransaction();
command.Parameters.Add(new SqlParameter("LocationBinId",locationBinId)); //not finding SQLParameter method
using (var dataReader = await command.ExecuteReaderAsync())
{
var result = new List<SynchStockDto>();
while (dataReader.Read())
{
var stockItem = new SynchStockDto
{
};
result.Add(stockItem);
}
return result;
}
}

Entity Framework (Telerik) call fails with ExecuteNonQuery to PostgreSQL stored procedure

(PostgreSQL 9.1, Telerik OpenAccess v2.0.50727, PgAdmin III).
I'm having difficulty calling a stored procedure from the (Telerik) Entity Framework. The exact error is:
NpgsqlException was unhandled by user code.
ERROR: 42703: column "cpatient" does not exist.
The Telerik templated call is:
public int SaveDx(string cpatient, Object o, Object n)
{
OAParameter parameterCpatient = new OAParameter();
parameterCpatient.ParameterName = "cpatient";
parameterCpatient.Size = -1;
if(cpatient != null)
{
parameterCpatient.Value = cpatient;
}
else
{
parameterCpatient.DbType = DbType.String;
parameterCpatient.Value = DBNull.Value;
}
OAParameter parameterO = new OAParameter();
parameterO.ParameterName = "o";
parameterO.Value = o;
OAParameter parameterN = new OAParameter();
parameterN.ParameterName = "n";
parameterN.Value = n;
int queryResult = this.ExecuteNonQuery("SELECT * FROM \"public\".\"g_savedx\"(cpatient, o, n)", CommandType.Text, parameterCpatient, parameterO, parameterN);
return queryResult;
}
Where the ExecuteNonQuery statement generates the error. The PostgreSQL stored procedure is:
FUNCTION g_savedx(cpatient character varying, o view_dx, n view_dx)
RETURNS void AS ...
The postgreSQL function has been tested to work correctly from pgAdmin.
So where is the column "cpatient" coming from?? What am I doing wrong?
TIA
I never could get the Telerik EntitiesModel ExecuteNonQuery to work under any conditions. Hence the suggested code of:
using (var cxt = new Nova.Data.Data())
{
cxt.SaveDx();
cxt.SaveChanges();
}
where cxt.SaveDx() is the domain model name for the postgresql g_savedx stored procedure, fails.
My eventual workaround for PostgreSQL is to use Npgsql directly as:
public void SaveDx(View_dx dx, bool alldx = false)
{
using (var cxt = new Nova.Data.Data())
{
string connstring = cxt.Connection.ConnectionString;
using (NpgsqlConnection conn = new NpgsqlConnection(connstring))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "g_savedx";
cmd.CommandType = CommandType.StoredProcedure;
NpgsqlCommandBuilder.DeriveParameters(cmd);
cmd.Parameters["groupid"].Value = ....
var rowsAffected = cmd.ExecuteNonQuery();
}
}
}
}
When doing it this way, only use the types defined in the NpgsqlDbType enumeration in the PostgreSQL procedure interface. (PostgreSQL can use composite types, Npgsql not so much).
It would sure be nice for Telerik ExecuteNonQuery to work.

RuntimeBinderException: Convert type System.Threading.Tasks.Task<object> to string

I do an example with signalR. But it doesn't function because of one mistake.
The one mistake (can not convert type system.threading.tasks.task< object> to string) is in this line:
return context.Clients.All.RecieveNotification(simple);
It is at the bottom of the code you can see below.
Below you see the method I wrote. There I do a connection with the database and get the content with a command/query.
Then a few checks and also SqlDependency.
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string query = "SELECT eintrag FROM [dbo].[simple_column]";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
simple = dt.Rows[0]["eintrag"].ToString();
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RecieveNotification(simple);
}
And here I use the function:
var notifications = $.connection.notificationHub;
notifications.client.recieveNotification = function (simple) {
// Add the message to the page.
$('#dbMessage').text(simple);
};
I hope you can help me.
Thanks.

Can I dispose a DataTable and still use its data later?

Noob ADO.NET question: Can I do the following?
Retrieve a DataTable somehow.
Dispose it.
Still use its data. (But not send it back to the database, or request the database to update it.)
I have the following function, which is indirectly called by every WebMethod in a Web Service of mine:
public static DataTable GetDataTable(string cmdText, SqlParameter[] parameters)
{
// Read the connection string from the web.config file.
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/WSProveedores");
ConnectionStringSettings connectionString = configuration.ConnectionStrings.ConnectionStrings["..."];
SqlConnection connection = null;
SqlCommand command = null;
SqlParameterCollection parameterCollection = null;
SqlDataAdapter dataAdapter = null;
DataTable dataTable = null;
try
{
// Open a connection to the database.
connection = new SqlConnection(connectionString.ConnectionString);
connection.Open();
// Specify the stored procedure call and its parameters.
command = new SqlCommand(cmdText, connection);
command.CommandType = CommandType.StoredProcedure;
parameterCollection = command.Parameters;
foreach (SqlParameter parameter in parameters)
parameterCollection.Add(parameter);
// Execute the stored procedure and retrieve the results in a table.
dataAdapter = new SqlDataAdapter(command);
dataTable = new DataTable();
dataAdapter.Fill(dataTable);
}
finally
{
if (connection != null)
{
if (command != null)
{
if (dataAdapter != null)
{
// Here the DataTable gets disposed.
if (dataTable != null)
dataTable.Dispose();
dataAdapter.Dispose();
}
parameterCollection.Clear();
command.Dispose();
}
if (connection.State != ConnectionState.Closed)
connection.Close();
connection.Dispose();
}
}
// However, I still return the DataTable
// as if nothing had happened.
return dataTable;
}
The general rule is to Dispose anything that implements IDisposable, whether it "needs it" or not. Saves you from the times when it "needs it" and you didn't think to Dispose.
Once you've called Dispose on an object, you shouldn't use it anymore. Period. It violates the entire concept of Dispose.
This is why you shouldn't call Dispose on an object that you are returning from a method. Leave it up to the caller to call Dispose when they're done with the object.
BTW, your code could be simpler. More like this:
using (SqlConnection connection = new SqlConnection(connectionString.ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(cmdText, connection))
{
//...
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
}
}
Well, you can't have your cake and eat it :)
Close the connection and so on, sure, but why do you need to dispose the table? That's not necessary. Just return it as-is.
Otherwise you'd be in a position where you... copy the table to something else and then return that instead? If you were using a ORM for example and mapping data to objects and then returning the objects this would make sense, but if you're not then just use the table/dataset directly.

How update DB table with DataSet

I am begginer with ADO.NET , I try update table with DataSet.
O client side I have dataset with one table. I send this dataset on service side (it is ASP.NET Web Service).
On Service side I try update table in database, but it dont 't work.
public bool Update(DataSet ds)
{
SqlConnection conn = null;
SqlDataAdapter da = null;
SqlCommand cmd = null;
try
{
string sql = "UPDATE * FROM Tab1";
string connStr = WebConfigurationManager.ConnectionStrings["Employees"].ConnectionString;
conn = new SqlConnection(connStr);
conn.Open();
cmd=new SqlCommand(sql,conn);
da = new SqlDataAdapter(sql, conn);
da.UpdateCommand = cmd;
da.Update(ds.Tables[0]);
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn != null)
conn.Close();
if (da != null)
da.Dispose();
}
}
Where can be problem?
It is better to look how really ADO.Net dataset works.
http://support.microsoft.com/kb/308507