How can I check results for select statement in MVC? - asp.net-mvc

Hi this is the SP I have :
USE [Tracker_Entities]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[uspHub]
#id int
AS
BEGIN
SELECT DISTINCT table1.UID, table1.url, Scope.ID
FROM table1 INNER JOIN
Scope ON table1.UID = Scope.newBrand
WHERE (table1.value = 0) AND (Scope.ID = #id)
ORDER BY table1.url
END
GO
When i run this SP in sql server by passing ID as parameter i am getting expected result. Now I need to check this SP in mvc. This is the way I am calling this SP in my MVC :
using (var ctx = new database_Entities())
{
int ID = 122;
ctx.uspHub(ID);
ctx.SaveChanges();
}
But when I put breakpoint in using statement and check for results, it is not displaying any results. I am struggling here for long time and i am not getting proper solution for this. So what are the steps in MVC to check results for SP which has select statements??
Update :
I got solution for this after using tolist. Now i am getting three results in list and i need to grab one result that is URL and pass it as input parameter.
My code :
int ID = 413;
var x = ctx.uspdHub(ID).ToList();
Here x has 3 results. I need to take one result from it.I tried doing x. but it doesn't show results after i type dot. How can i achieve this??

You have to Get the result into proper model/object.
List<YourEntity> model;
using (var ctx = new database_Entities())
{
int ID = 122;
model = ctx.uspHub(ID).toList();
//ctx.SaveChanges(); - no need to call SaveChanges
// - as you are not updating anything
}
Go through this article if you need more info. Call Stored Procedure From Entity Framework (The code above will work anyways...)

use...
using (var ctx = new database_Entities())
{
int ID = 122;
var result = ctx.uspHub(ID);
}
and add a break after the result to see whats in the result variable. Obviously, the sope of result will need to be moved, but I'm only showing here how you can see the data returned.

Try to use something like this:
using (var dataContext= new database_Entities())
{
int ID = 122;
SomeEntity[] result = dataContext.Database.SqlQuery<SomeEntity>("[dbo].[uspHub] #id",new SqlParameter("#id", ID)).ToArray();
}
It is good for me. I have used ORM EntityFramework to connect with DB.

Related

dapper querymultiple spliton error

I'm using: ASP.NET MVC, MySql, Dapper.NET micro-orm
I made a stored procedure with 3 SELECTs, two of which returns lists and the third one returns an integer.
Here is my code:
using (var conn = new MySqlConnection(GetConnectionString()))
{
var readDb = conn.QueryMultiple(storedProcedure, parameters, commandType: CommandType.StoredProcedure);
var result = new someView
{
TopicsList = readDb.Read<ITopic>().ToList(),
TopTopicsList = readDb.Read<IMessage>().ToList(),
TopicsCount = readDb.Read<int>().Single()
};
return result;
}
In ITopic I have TopicId, in IMessage I have MessageId.
And here's the error:
When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id Parameter name: splitOn
I tried adding splitOn on both QueryMultiple and Read, and nigher accepted it.
Though I dont understand why I need splitOn? can't dapper see that I have three separate SELECTs? When using conn.Read(storedProcedure,parameters) on each of the selects separately (instead of MultipleQuery on all of the together) dapper has no problem mapping it to a given object.
What am I doing wrong?
1) Problem solved when I used the real models names instead of their interfaces names:
TopicView instead of ITopic, TopTopicsView instead of IMessage;
2) Once that was fixed and there was no longer "no splitOn" error, started another problem with the < int > casting in line:
TopicsCount = readDb.Read<int>().Single()
probably mysql doesnt return numbers back as ints?
I tried using decimal, object, dynamic, etc.. with no luck. Eventually fixed it by creating another Model with int property inside that has the same name as the database int parameter and now it works.
3) Here's the final working code:
using (var conn = new MySqlConnection(GetConnectionString()))
{
var parameters = context.MapEntity(query);
var multi = conn.QueryMultiple(storedProcedure, parameters, commandType: System.Data.CommandType.StoredProcedure);
var TopicsList = multi.Read<TopicView>().ToList();
var TopTopicsList = multi.Read<TopTopicsView>().ToList();
var result = multi.Read<HomeView>().Single();
result.TopicsList = TopicsList;
result.TopTopicsList = TopTopicsList;
return result;
}

Filtering list using linq and mvc

Below is the code in question. I receive Object reference not set to an instance of an object. on the where clause inside the Linq query. However, this only happens after it goes through and builds my viewpage.
Meaning: If I step through using debugger, I can watch it pull the correct order I am filtering for, go to the correct ViewPage, fill in the model/table with the correct filtered item, and THEN it comes back to my Controller and shows me the error.
public ActionResult OrderIndex(string searchBy, string search)
{
var orders = repositoryOrder.GetOpenOrderList();
if (Request.QueryString["FilterOrderNumber"] != null)
{
var ordersFiltered = from n in orders
where n.OrderNumber.ToUpper().Contains(Request.QueryString["FilterOrderNumber"].ToUpper().ToString())
select n;
return View(ordersFiltered);
}
return View(orders);
}
its always better to manipulate your strings and other things outside the linq query ,
please refer : http://msdn.microsoft.com/en-us/library/bb738550.aspx
from the readability point of view also its not good ,
public ActionResult OrderIndex(string searchBy, string search)
{
var orders = repositoryOrder.GetOpenOrderList();
var orderNumber = Request.QueryString["FilterOrderNumber"];
if (!string.IsNullOrEmpty(orderNumber))
{
orderNumber = orderNumber.ToUpper();
var ordersFiltered = from n in orders
where n.OrderNumber.ToUpper().Contains(orderNumber)
select n;
return View(ordersFiltered);
}
return View(orders);
}
Your query is not being executed in your Action method because you don't have a ToList (or equivalent) added to your query. When your code returns, your query will be enumerated somewhere in your view and that's the point where the error occurs.
Try adding ToList to your query like this to force query execution in your action method:
var ordersFiltered = (from n in orders
where n.OrderNumber.ToUpper().Contains(Request.QueryString["FilterOrderNumber"].ToUpper().ToString())
select n).ToList();
What's going wrong is that a part of your where clause is null. This could be your query string parameter. Try moving the Request.QueryString part out of your query and into a temporary variable. If that's not the case make sure that your orders have an OrderNumber.
You both were right. Just separately.
This fixed my problem
var ordersFiltered = (from n in orders
where !string.IsNullOrEmpty(n.OrderNumber) && n.OrderNumber.ToUpper().Contains(Request.QueryString["FilterOrderNumber"].ToUpper().ToString())
select n);

How can I update table in Entity framework?

I am calling a web service from my MVC project and if it is successful then it returns process complete. This result, I am storing in variable called y.
var y = Here pass required parameters and if it is successfull store result in y
when I put breakpoint here and if process complete, I can see result in var y.
So if process complete I need to update my table. For this can I do like this ?
if( y = "Process complete")
{
update table code here
}
and I don't know how to update table in Entity Framework. Here I need to update table called table1 and set column2 = 1, column 3 = value of column 4 where column 1 = value of column 1.
What I know for this is :
UPDATE tableName
SET column2 = 1, column3 = context.FirstOrDefault().column4
WHERE column1 = context.FirstOrDefault(). column1
Update :
Hi i got to know how to write code to update table.But when i put break-point and come to savechanges method i am getting Property export is part of the objects key information and cannot be modified error.
This is the code i am using to update my table :
var rec = (from s in geton.table_1
where s.on_id == geton.table_1.FirstOrDefault().on_id
select s).FirstOrDefault();
rec.export = 1;
rec.on_date = geton.table_1.FirstOrDefault().on_date;
geton.SaveChanges();
A new entity can be added to the context by calling the Add method on DbSet. This puts the entity into the Added state, meaning that it will be inserted into the database the next time that SaveChanges is called.
For example:
using (var context = new YourContext())
{
var record = new TypeName { PropertyName = "Value" };
context.EntityName.Add(record );
context.SaveChanges();
}
For More Info :
http://msdn.microsoft.com/en-us/library/bb336792.aspx
http://msdn.microsoft.com/en-us/data/jj592676.aspx
http://www.entityframeworktutorial.net/significance-of-savechanges.aspx
Hi i got to know how to write code to update table.But when i put break-point and come to savechanges method i am getting Property export is part of the objects key information and cannot be modified error.
That sounds more like a Key error. Are you sure you have put a primary key on that table?
If not then EF just uses the whole table as the key essentially

Passing query parameters in Dapper using OleDb

This query produces an error No value given for one or more required parameters:
using (var conn = new OleDbConnection("Provider=..."))
{
conn.Open();
var result = conn.Query(
"select code, name from mytable where id = ? order by name",
new { id = 1 });
}
If I change the query string to: ... where id = #id ..., I will get an error: Must declare the scalar variable "#id".
How do I construct the query string and how do I pass the parameter?
The following should work:
var result = conn.Query(
"select code, name from mytable where id = ?id? order by name",
new { id = 1 });
Important: see newer answer
In the current build, the answer to that would be "no", for two reasons:
the code attempts to filter unused parameters - and is currently removing all of them because it can't find anything like #id, :id or ?id in the sql
the code for adding values from types uses an arbitrary (well, ok: alphabetical) order for the parameters (because reflection does not make any guarantees about the order of members), making positional anonymous arguments unstable
The good news is that both of these are fixable
we can make the filtering behaviour conditional
we can detect the category of types that has a constructor that matches all the property names, and use the constructor argument positions to determine the synthetic order of the properties - anonymous types fall into this category
Making those changes to my local clone, the following now passes:
// see https://stackoverflow.com/q/18847510/23354
public void TestOleDbParameters()
{
using (var conn = new System.Data.OleDb.OleDbConnection(
Program.OleDbConnectionString))
{
var row = conn.Query("select Id = ?, Age = ?", new DynamicParameters(
new { foo = 12, bar = 23 } // these names DO NOT MATTER!!!
) { RemoveUnused = false } ).Single();
int age = row.Age;
int id = row.Id;
age.IsEqualTo(23);
id.IsEqualTo(12);
}
}
Note that I'm currently using DynamicParameters here to avoid adding even more overloads to Query / Query<T> - because this would need to be added to a considerable number of methods. Adding it to DynamicParameters solves it in one place.
I'm open to feedback before I push this - does that look usable to you?
Edit: with the addition of a funky smellsLikeOleDb (no, not a joke), we can now do this even more directly:
// see https://stackoverflow.com/q/18847510/23354
public void TestOleDbParameters()
{
using (var conn = new System.Data.OleDb.OleDbConnection(
Program.OleDbConnectionString))
{
var row = conn.Query("select Id = ?, Age = ?",
new { foo = 12, bar = 23 } // these names DO NOT MATTER!!!
).Single();
int age = row.Age;
int id = row.Id;
age.IsEqualTo(23);
id.IsEqualTo(12);
}
}
I've trialing use of Dapper within my software product which is using odbc connections (at the moment). However one day I intend to move away from odbc and use a different pattern for supporting different RDBMS products. However, my problem with solution implementation is 2 fold:
I want to write SQL code with parameters that conform to different back-ends, and so I want to be writing named parameters in my SQL now so that I don't have go back and re-do it later.
I don't want to rely on getting the order of my properties in line with my ?. This is bad. So my suggestion is to please add support for Named Parameters for odbc.
In the mean time I have hacked together a solution that allows me to do this with Dapper. Essentially I have a routine that replaces the named parameters with ? and also rebuilds the parameter object making sure the parameters are in the correct order.
However looking at the Dapper code, I can see that I've repeated some of what dapper is doing anyway, effectively it each parameter value is now visited once more than what would be necessary. This becomes more of an issue for bulk updates/inserts.
But at least it seems to work for me o.k...
I borrowed a bit of code from here to form part of my solution...
The ? for parameters was part of the solution for me, but it only works with integers, like ID. It still fails for strings because the parameter length isn't specifed.
OdbcException: ERROR [HY104] [Microsoft][ODBC Microsoft Access Driver]Invalid precision value
System.Data.Odbc. OdbcParameter.Bind(OdbcStatementHandle hstmt,
OdbcCommand command, short ordinal, CNativeBuffer parameterBuffer, bool allowReentrance)
System.Data.Odbc.OdbcParameterCollection.Bind(OdbcCommand command, CMDWrapper cmdWrapper, CNativeBuffer parameterBuffer)
System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader, object[] methodArguments, SQL_API odbcApiMethod)
System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader)
System.Data.Common.DbCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
Dapper.SqlMapper.QueryAsync(IDbConnection cnn, Type effectiveType, CommandDefinition command) in SqlMapper.Async.cs
WebAPI.DataAccess.CustomerRepository.GetByState(string state) in Repository.cs
var result = await conn.QueryAsync(sQuery, new { State = state });
WebAPI.Controllers.CustomerController.GetByState(string state) in CustomerController .cs
return await _customerRepo.GetByState(state);
For Dapper to pass string parameters to ODBC I had to specify the length.
var result = await conn.QueryAsync<Customer>(sQuery, new { State = new DbString { Value = state, IsFixedLength = true, Length = 4} });

how to execute MYSQL stored procedure in zend framework 2 with multiple result set

How to execute MYSQL stored procedure in zend framework 2 with multiple result set means if sp have multiple select query then how can i get all the result in array and how i pass dynamic value in sp for insert and update data in table.
thanks..
I recently wrote a small article about this. The solution I found is not a generic one and assumes that you are using PDO. I am not sure whether it works with other databases than MySQL. It is possible that there is a better and more generic way of doing this that I am not aware of.
$driver = $this->dbAdapter->getDriver();
$connection = $driver->getConnection();
$result = $connection->execute('CALL sp_get_profile_for_display (123)');
$statement = $result->getResource();
// Result set 1
$resultSet1 = $statement->fetchAll(\PDO::FETCH_OBJ);
foreach ($resultSet1 as $row) {
$something = $row->some_column;
}
// Result set 2
$statement->nextRowSet(); // Advance to the second result set
$resultSet2 = $statement->fetchAll(\PDO::FETCH_OBJ);
foreach ($resultSet2 as $row) {
/* Do something */
}
// Result set 3
$statement->nextRowSet(); // Advance to the third result set
$resultSet3 = $statement->fetchAll(\PDO::FETCH_OBJ);
foreach ($resultSet3 as $row) {
/* Do something */
}
Replace the 123 with the data you wish to pass to the stored procedure as a parameter. If using user supplied data, remember to escape it to prevent SQL injection!

Resources