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

(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.

Related

Login failed. The login is from an untrusted domain and cannot be used with Integrated authentication. in Entity Framework

getting {"Login failed. The login is from an untrusted domain and cannot be used with Integrated authentication."} please give any suggetion why this error is throwing.
public int Find(string AccountNumber, DateTime DepositedDT)
{
IsPigmySync pigmySync = new IsPigmySync();
pigmySync.AccountNumber = AccountNumber;
pigmySync.DepositedDT = DepositedDT;
SqlParameter issynced = new SqlParameter("#p2", System.Data.SqlDbType.Int);
issynced.Direction = ParameterDirection.Output;
try
{
var sql = "exec Pigmy_GetPigmyItems #p0,#p1,#p2 OUT";
// var result = _context.Database.ExecuteSqlInterpolated(sqlQuery);
var result = _context.Database.ExecuteSqlCommand(sql, pigmySync.AccountNumber, pigmySync.DepositedDT, issynced);
int ab = result;
pigmySync.IsSynced = (int)issynced.Value;
return pigmySync.IsSynced;
}
catch (Exception ex)
{
return 0;
}
above is my code snippet. using entity framework,xamarin forms

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;
}
}

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

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;
}

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.

One to Many And Many To One Insert in Ef 6.0

A doctor have one degree and one degree have many doctors,
well when i try to add new doctor ef 6.0 (DbContext) insert the selected degree as new record in Degress Table
i don know why ?
Insert Method :
public bool Insert<T>(T entity) where T : class
{
bool result = false;
try
{
Context.Set<T>().Add(entity);
result = Context.SaveChanges() > 0;
}
catch (Exception exp)
{
result = false;
fnLogExceptions(exp);
}
return result;
}
The insert Section :
private void btnSave_Click(object sender, EventArgs e)
{
var dr = new DB.Doctors();
...
dr.Degrees = dropDownList_Degree.SelectedItem as DB.Degrees;
...
using (var ctx = new Context())
{
opState = ctx.Insert<DB.Doctors>(dr);
}
...
}
the new doctor is inserted successfully but also it insert new copy of selected degree
thanks in advance
The Degree that you were trying to assign isn't from the database, its from the dropodown list. So the EF thinks its new, therefore inserting a new Degree.
You need to retrieve the existing degree from the database.
var dr = new DB.Doctors();
int selectedDegreeID = (int)dropDownList_Degree.SelectedItem.Value;
using (var ctx = new Context())
{
dr.Degree = ctx.Degrees.Find(selectedDegreeID); // Retrieval and assignment.
opState = ctx.Insert<DB.Doctors>(dr);
}