I'm using asp.net to process a SQL query that returns a column from some table. Normally what I'd do is set a variable equal to the stored procedure function call and add .ToArray() at the end, which is what I want to do here but I'm getting an error message int does not contain a definition for toarray...
I'm confused because I followed the same syntax that I used in another part of the program for a similar thing. It worked fine before but I can't figure out why it wants to fight with me now.
Here's my SQL:
IF OBJECT_ID('#temp') IS NOT NULL
BEGIN
DROP TABLE #temp
END
--Create temp table to store data
CREATE TABLE #temp
(
EventID nvarchar(50),
RunDate date,
SectionCode nvarchar(50),
SectionMapCode nvarchar(50),
DispSort int,
Capacity int,
Attendance int,
PctCap int,
HeatColor nvarchar(50)
)
DECLARE #runDate date = GETDATE()
INSERT #temp Exec GamedayReporting.dbo.uspGetEventKillSheetDetailedReport #EventID, #runDate;
select Capacity from #temp;
This returns exactly what I want in SQL but when I call it in my Controller I get the error I posted above.
Here's my C# code:
public ActionResult Dropdown()
{
// add your code after post method is done
var selectedOption = Request["eventId"];
var date = DateTime.Today;
var myQuery = db.uspGetEventKillSheetDetailedReport(selectedOption, date).ToArray();
ViewData["query"] = myQuery;
System.Diagnostics.Debug.WriteLine(myQuery);
TempData["option"] = selectedOption;
return RedirectToAction("Map");
}
public ActionResult Map()
{
var secAttendance = db.uspGetSectionAttendance("option").ToArray();
var secCapacity = db.uspGetSecCapacity("option");
var secMapCode = db.uspGetSectionMapCode("option");
}
public JsonResult GetDropdownList()
{
var ids = db.uspGetAllEventIds().ToArray();
ViewData["ids"] = db.uspGetAllEventIds().ToArray();
return Json(new { data = ids }, JsonRequestBehavior.AllowGet);
}
So Dropdown() and GetDropdownList() work fine, but I'm getting the problem with Map().
Basically I want to take the column returned from my SP and store it into an array but it won't let me. Anybody able to help me work through this?
Update
I changed .ToArray() to .toString().toArray(), which got me past the compiler error, but upon logging it into the console I found it was returning char instead of string. So I changed the whole line to
string secAttendance = new string(db.uspGetSectionAttendance("option").ToString().ToArray());
and output the result into the console and found it returns 0.
0 comes from the Return Value in SQL, which I don't understand. It will fetch the correct column but will not send the correct data to ASP.
Here's a screenshot of the output from my SQL:
The error is correct. There must be only one row, one column value in the output. You are selecting
select Capacity from #temp;
which returns a single value as an int.
It cannot be directly cast into an array.
Instead, if you want an array, you can create a blank
Array<int> a = new Array<int>[1]
and then push this output to that array.
Related
Previously this worked well and recently the line stop working. This code uses the DB context to run a procedure and return it in List format. For some reason I am not seeing the error, I just see the action fail because it is not executing.
I ran the stored procedure in SQL Server and see the desired results, just not seeing it happening from the application layer.
[Http.Route("postsearch")]
public async Task<IHttpActionResult> PostSearch(SearchInputDTO srequest)
{
var searchString = srequest.SearchValue.ToString();
List<output> seResult = new List<output>(_output.searchLog(searchString)); /*This line stopped working*/
return Ok(seResult);
}
Stored procedure:
SET FMTONLY OFF
GO
SET NOCOUNT ON
GO
ALTER PROCEDURE [dbo].[searchLog]
#searchValue VARCHAR(150)
AS
SELECT *
FROM [dbo].[output]
WHERE CONTAINS (*, #searchValue)
Implementation in Entity Framework
public virtual int searchLog(string searchValue)
{
var searchValueParameter = searchValue != null ?
new ObjectParameter("searchValue", searchValue) :
new ObjectParameter("searchValue", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("searchLog", searchValueParameter);
}
This should return the rows from the query.
The Solution I found was to modify the output of the stored procedure in Visual Studio.
Try removing the new instance of the list and just have it like this
List<output> seResult = _output.searchLog(searchString);
Update stored proc to
#searchValue varchar(150)
AS
BEGIN
SELECT
[ColumnName1]
,[ColumnName2] ...etc...
FROM [dbo].[output]
WHERE CONTAINS (*,#searchValue)
END
I have a field where i'm counting the total number of subscriptions to an user. Right now i update this field like this:
using (var context = new AppDbContext())
{
var foundEntry = context.Users.Find(id);
if (foundEntry != null)
{
foundEntry.TotalSubscriptions = foundEntry.TotalSubscriptions + 1;
context.Entry(foundEntry).CurrentValues.SetValues(foundEntry);
var result = context.SaveChanges();
}
}
But this way i have to make 2 queries to the db. One to get the current total count and one to update the value.
Is there a way to do this with only one query to the db with entity framework?
I wanted to try something like this:
var user = new User() { Id = userId, TotalSubscriptions = currentS + 1 };
db.Users.Attach(user);
db.Entry(user).Property(x => x.TotalSubscriptions).IsModified = true;
but the problem i'm facing is that i would have to get the current count first but don't know how to do in in a single query. I think that 1 query for this is possible with a raw SQL statement/query.
I'm trying to archive something like this: https://stackoverflow.com/a/2762856/1286942 but with entity framework.
UPDATE
I also tried something like this:
var user = new User() { Id = userId };
db.Users.Attach(user);
user.TotalSubscriptions = context.Entry(user)
.Property(u => u.TotalSubscriptions).OriginalValue + 1;
db.Entry(user).Property(x => x.TotalSubscriptions).IsModified = true;
But the problem is that the .OriginalValue and the .OriginalValue always return 0. So the TotalSubscriptions field is always updated to -1 or 1.
UPDATE #2
Right now i see only this as an option:
var numberOfUpdatedRows = context.Database
.ExecuteSqlCommand("UPDATE dbo.Users
SET TotalSubscriptions = TotalSubscriptions + 1
WHERE id = " + id + "");
The basic approach for this type of code is to use a stored procedure for your SQL code, and pass in a variable value to the procedure. Here is a possible solution for your problem.
CREATE PROCEDURE AdjustSubscriptions
#userid int,
#adjustment int
AS
BEGIN
DECLARE #subs int
SET NOCOUNT ON
UPDATE UserInfo
SET #subs = currentS + #adjustment, currentS = #subs
WHERE userID = #userid
SELECT #subs AS SubscriptionCount
END
This will SELECT the currentS value into a variable, adjust it as specified by the value in #adjustment, (Adding three subscriptions? Pass a three. Removing three subscriptions? Pass a negative three) then UPDATE the value to the saved row. Finally, a row containing only the adjusted subscriptionCount value is returned.
The stored procedure could be rewritten to return the value in an OUTPUT variable (if implemented correctly, you will simply get the value back into a variable instead of having to deal with a recordset), or even use the statement RETURN #subs at the end of the procedure to return the adjusted value as a return value. I highly recommend that you do NOT use the RETURN #subs method, since it breaks on a return of a string or a value outside of smallint.
I leave it to you to implement the entity framework code to handle the stored procedure. I don't believe that you can do the same direct manipulation of the value using one call within the entity framework, but I'm perfectly willing to be shown otherwise.
Happy Coding.
have a stored Procedure that do some operation and return 1 or 0 as below.
CREATE PROCEDURE dbo.UserCheckUsername11
(
#Username nvarchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
IF Exists(SELECT UserID FROM User WHERE username =#Username)
return 1
ELSE
return 0
END
Using linq I tried to get return value. But i am getting the output as -1 always.
Below is my Linq code :
using (PlanGenEntities3 entity2 = new PlanGenEntities3())
{
var result = entity2.Entity_test_GetHoliday();
string output = result.ToString();
}
How to solve this ?
Just declare your scalar variable as a output parameter for SQL query, then in the code you could retrieve its value this way:
```
using (PlanGenEntities3 myContext = new PlanGenEntities3())
{
var outputParameter = new System.Data.Objects.ObjectParameter("OutputParameterName", typeof(int));
myContext.Entity_test_GetHoliday(outputParameter );
Console.WriteLine(outputParameter.Value);
}
```
I suppose there is way to access the default scalar output of your SP in the similar manor.
If he had it as an output parameter it would automatically show as a reference parameter of the proper corresponding data type in the LINQ call.
He wouldn't really need to create a parameter object to contain that.
alter procedure [dbo].[XXX]
(
#vendorworksationID uniqueidentifier ,
#sdate date,
#edate date,
#total int out
)
begin
select #total = COUNT(*)
from AdvertisedCampaignHistory a
where
CAST(a.CreationDate AS DATE) BETWEEN CAST(#sdate as DATE) AND CAST(#edate as DATE)
and a.CampaignID in (select cc.BCampaignID
from BeaconCampaign cc, VendorWorkStation vw
where cc.VendorWorkStationID = vw.VendorWorkStationID
and VendorID = #vendorworksationID)
return #total
end
The above code shows the stored procedure that return an integer value from SQL Server
ObjectParameter Output = new ObjectParameter("total", typeof(Int32));
var resBC = this.Context.getTotalSentBeaconCampaign(VendorWorkstationID, sdate,edate,Output).FirstOrDefault();
The above code shows how I am passing parameters and retrieving the value on the C# side
While running the code I am getting following error
The data reader returned by the store data provider does not have
enough columns for the query requested.
What could be the possible cause for this error?
Entity Framework cannot support Stored Procedure Return scalar values out of the box.To get this to work with Entity Framework, you need to use "Select" instead of "Return" to return back the value.
More Ref : http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values
I have an existing Stored Procedure which I am trying to now call with LINQ to SQL, here is the stored procedure:
ALTER procedure [dbo].[sp_SELECT_Security_ALL] (
#UID Varchar(15)
)
as
DECLARE #A_ID int
If ISNULL(#UID,'') = ''
SELECT DISTINCT
App_ID,
App_Name,
App_Description,
DB,
DBNameApp_ID,
For_One_EVA_List_Ind
From v_Security_ALL
ELSE
BEGIN
Select #A_ID = (Select Assignee_ID From NEO.dbo.v_Assignees Where USER_ID = #UID and Inactive_Ind = 0)
SELECT DISTINCT
Security_User_ID,
Security_Company,
Security_MailCode,
Security_Last_Name,
Security_First_Name,
Security_User_Name,
Security_User_Info,
Security_User_CO_MC,
Security_Email_Addr,
Security_Phone,
Security_Security_Level,
Security_Security_Desc,
Security_Security_Comment,
Security_Security_Inactive_Ind,
App_ID,
App_Name,
App_Description,
DB,
DBNameApp_ID,
For_One_EVA_List_Ind,
#A_ID as Assignee_ID
From v_Security_ALL
Where Security_User_ID = #UID
END
My problem is that the intellsense only sees the first set of return values in the IF statement and I can not access anything from the "else" part of my stored procedure. so when I try to do this:
var apps = dataContext.sp_SELECT_Security_ALL(userId);
foreach (var app in apps)
{
string i = app.
}
On the app. part the only available values I have there is the results of the the first Select distinct above.
Is it possible to use LINQ with this type of stored procedure?
Scott Guthrie has covered this case in a blog post. Scroll down to "Handling Multiple Result Shapes from SPROCs."
The problem isn't with Intellisense. dataContext.sp_SELECT_Security_ALL() is returning a fixed data type. You may be hiding that behind a "var", but it's nevertheless a concrete type with a fixed number of properties. There is still C# remember, and a function can only return one type of object. Look in your dataContext.designer.cs file to see how it's actually defined.
The quick and dirty way to fix this is to coerce every returning statement to return the same thing:
IF #theSkyIsBlue
SELECT CustomerNumber, CustomerName, null as OrderNumber, null as OrderName
FROM Customers
ELSE
SELECT null as CustomerNumber, null as CustomerName, OrderNumber, OrderName
FROM Orders
You may have to watch/(manually change) the nullability of properties in the mapped type, but this will get you where you're going.