Sequence contains no elements... Thing is, I know it should - c#

Background:
Using C# in the ASP.Net code-behind to call a SQL stored procedure via LINQ-to-Entities.
Also, please note that I am a complete newbie to all of this.
Problem:
I'm calling a stored procedure to get the max_length of a column in my database.
It keeps returning "Sequence Contains No Elements" when utilizing .First() and (alternately) the default when using .FirstOrDefault().
The problem is, I know it should be returning the number "4500" as I've run the query in SQL to see what should be there.
Any ideas on why it would be doing this?
I've searched high and low, but I can't find anyone else who has had this problem where they know it should be returning a value.
Code:
short? `shorty = db.sp_GetMaxLength("ApplicantEssay").First();`
The result of the SQL query used in the stored procedure:
Thanks so much for any assistance you can provide!!
Edit:
The only other code involved is the ADO.Net Entity auto-generated code.
At least, it's the only other code that the program steps through when I tried to examine what was going on.
I had a hard time looking at the return and trying to figure it out, but obviously it's returning nothing):
public virtual ObjectResult<Nullable<short>> sp_GetMaxLength(string cOLUMN_NAME)
{
var cOLUMN_NAMEParameter = cOLUMN_NAME != null ?
new ObjectParameter("COLUMN_NAME", cOLUMN_NAME) :
new ObjectParameter("COLUMN_NAME", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<short>>("sp_GetMaxLength", cOLUMN_NAMEParameter);
}
Edit #2: I guess I should close this question out.
I messed around with some stuff in sql, then put it back to what I had in the first place and re-executed the stored procedure. Following that, I deleted the Entity Model, reset web.config to its original state pre-model, closed Visual studio, re-opened Visual Studio, and then re-added an ADO.Net Entity Model to the project. I then re-ran the code, stepped through it, and then all of a sudden, "4500" popped up as the returned value.
I am completely flummoxed, since all the code is exactly the same without changes, but I guess that's the power of scrapping and re-starting??? No other explanation, though I hate when it's as simple as that. :-(
Thanks to all who commented. :-)

Related

MVC: Timeout issue

I'm trying to extract the results of a SQL server view in MVC. The view itself is relatively straightforward and UNIONs a couple of tables together - when run it takes around 2 seconds to return its rows. I've added the view to my model in MVC.
In my controller I have the following code, which is designed to return in JSON format the values from the SQL view:-
public JsonResult GetActivity(string LocalIdentifier)
{
return Json(db.Activities.Where(r => r.LocalIdentifier== LocalIdentifier).ToList(), JsonRequestBehavior.AllowGet);
}
When I try to run this, supplying a valid LocalIdentifier nothing happens for a while and then I get an exception (unhandled in user code) in Visual Studio. For reference, this would generally only return between 30 and 50 rows of data from SQL.
Looking at the Inner Exception I get this error:-
"Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
I've done something similar elsewhere in my application and it works fine - I can't see anything wrong with my code in MVC. Is there anything else I could look at to help diagnose and fix this issue?
Update
Interestingly I've just changed the code to extract just one row (just to see what happens - see below) and it runs instantly...could this be a problem with ToList()?? Is there another way of achieving what I'm trying to do that I could try?
public JsonResult GetActivity(string LocalIdentifier)
{
return Json(db.Activities.First(r => r.LocalIdentifier== LocalIdentifier), JsonRequestBehavior.AllowGet);
}
you should try running the resulting query directly on the sql server. I expect that the query runs for more then 30s, resulting in a timeout. The default timeout value is 30s, so the behaviour you're seeing is expected.
2 ways to deal with it:
speed up the query (maybe you're missing an index?)
change the default timeout (but this is not the preferred option in my opinion)
It depends on how db.Activities is defined. If it has properties for other entities (meaning other tables in the database) then these could also be loaded by EF, even though you did not specify so explicitly, because JSON is serializing each object and its properties. Half your database or more could end up being loaded, even from a simple statement like this.
This SO question has several answers that may help you understand better what is going on behind the scenes, and then fix it.
Enable profiling and see the query inside
Launch this query in SSMS and build the query execution plan
Analyse the plan and make the updates to the database - change structure, build index, change query
If the query runs fine in DB then it seems something wrong with your ORM side part and you should search for the problem there

Using Linq with SQLite: Table recognized but "Results View" gives error

I'm trying to work with SQLITE in .
However I've faced a weird problem :
// Start of code
connection = new SQLiteConnection(myConnectionString);
connection.Open();
myDataContext = new Main(connection, new SqliteVendor());
// End of code
Examing 'myDataContext' after execution (with debugger), I see it has the type 'Main' (as should be :)) and also has as members,
the names of the tables I've defind in DB (so far - so good...), but...
Trying open one table (which has(!) records), and then trying to open the "ResultView" member of that table, I'm facing the string
"SQLite error\n No such table: main:XXXX"
(XXXX is the table name...)
(I've came to examine the structure because when I've tried to fetch records by linq command - I've got an exception.)
Do you have any idea what can cause this behavior?
Thanks,
Rivka
Ok, I've found the source of it...
(actually found it several hours after I've published the question...)
I'm working with visual studio and my DB file name is part of the project.
Since I've changed the (name and content...) of th db filename, i've forgot to mark
it "Copy Always"... That has caused the problem.
Please mark that as solved...

The riddle of the working broken query

I was going through some old code that was written in years past by another developer at my organization. Whilst trying to improve this code, I discovered that the query it uses had a very bad problem.
OdbcDataAdapter financialAidDocsQuery =
new OdbcDataAdapter(
#"SELECT a.RRRAREQ_TREQ_CODE,
b.RTVTREQ_SHORT_DESC,
a.RRRAREQ_TRST_DESC,
RRRAREQ_STAT_DATE,
RRRAREQ_EST_DATE,
a.RRRAREQ_SAT_IND,
a.RRRAREQ_SBGI_CODE,
b.RTVTREQ_PERK_MPN_FLAG,
b.RTVTREQ_PCKG_IND,
a.RRRAREQ_MEMO_IND,
a.RRRAREQ_TRK_LTR_IND,
a.RRRAREQ_DISB_IND,
a.RRRAREQ_FUND_CODE,
a.RRRAREQ_SYS_IND
FROM FAISMGR.RRRAREQ a, FAISMGR.RTVTREQ b
WHERE a.RRRAREQ_TREQ_CODE = b.RTVTREQ_CODE
and a.RRRAREQ_PIDM = :PIDM
AND a.RRRAREQ_AIDY_CODE = :AidYear ",
this.bannerOracle);
financialAidDocsQuery.SelectCommand.Parameters.Add(":PIDM", OdbcType.Int, 32).Value = this.pidm;
financialAidDocsQuery.SelectCommand.Parameters.Add(":AidYear", OdbcType.Int, 32).Value = this.aidYear;
DataTable financialAidDocsResults = new DataTable();
financialAidDocsQuery.Fill(financialAidDocsResults);
FADocsGridView.DataSource = financialAidDocsResults;
FADocsGridView.DataBind();
The problem is that the column a.RRRAREQ_TRST_DESC does not exist. A fact you learn very quickly when running it in Oracle SQL Developer.
The strange thing?
This code works.
The gridview binds successfully. (It doesn't try to bind to that field.) And it's been in production for years.
So, my question is...why? I've never seen a bad query work. I've never seen Oracle allow it or a data provider hack around it.
Does anyone have any idea what's going on here?
Hmmm...A few things to check:
Does this code actually run? It may seem silly to suggest this, but there may be a newer file that replaced this one.
Is an exception being squelched by your code? (Anyone who would name columns like that is definitely capable of squelching those pesky exceptions)
Is the exception being squelched by 3rd party code? (Not as likely, but sometimes 3rd party code prefers to use annoying error codes instead of exceptions).
Past those suggestions, I'm not sure.
EDIT:
Revisiting the 2nd point, if you are working in ASP.NET, check that there is no global-level exception handler that is squelching exceptions. I ran into that problem on one site that I worked on and found dozens of exceptions in a single day.
Try running
select * from v$sql where sql_fulltext like '%a.RRRAREQ_TRST_DESC%'
shortly after you bind the grid. That will tell you if the statement was actually seen by Oracle. Note that you should only see the above query if it was not seen by Oracle.
Use ODBC trace log to see if this query is really send to database, and see what database returns. Then use any other ODBC based database tool and check if this query work from this tool. As an ultimate test you can write simple Python script. Easiest way it to use ActiveState Python 2.x with odbc module included. Test code can look like:
import odbc
connection = odbc.odbc('dnsname/user/password')
cursor = connection.cursor()
cursor.execute("select ...")
for row in cursor.fetchall():
print '\t'.join([str(r) for r in row])
If there was no error in your program and an error in other tools then compare theirs ODBC traces.
If I understand what the original author was trying to do, and with Banner that is never easy to figure out, then this query should be correct:
SELECT a.rrrareq_treq_code,
b.rtvtreq_short_desc,
c.rtvtrst_desc,
rrrareq_stat_date,
rrrareq_est_date,
a.rrrareq_sat_ind,
a.rrrareq_sbgi_code,
b.rtvtreq_perk_mpn_flag,
b.rtvtreq_pckg_ind,
a.rrrareq_memo_ind,
a.rrrareq_trk_ltr_ind,
a.rrrareq_disb_ind,
a.rrrareq_fund_code,
a.rrrareq_sys_ind
FROM faismgr.rrrareq a,
faismgr.rtvtreq b,
faismgr.rtvtrst c
WHERE a.rrrareq_treq_code = b.rtvtreq_code
AND a.rrrareq_trst_code = c.rtvtrst_code
AND a.rrrareq_pidm = :PIDM
AND a.rrrareq_aidy_code = :AidYear;
Well, let's file this in the false alarm category.
I decided to have our VAT send a copy of the DLL from test. I pulled it apart with reflector and found, much to my embarrassment, that the query is right. Which makes sense.
I still can't figure out why my working copy would have one incorrect field_name. To my knowledge, I had never touched this file before this week. But, SVN doesn't have any history showing this error in previous versions.
So strange...maybe I'm losing my mind.
Thanks for all of the quality feedback on this question. I certainly learned some new trouble shooting techniques and for that I'm very appreciative. :)
Happy coding,
Clif

DataTableReader is invalid for current DataTable 'TempTable' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm getting the following error whenever my code creates a DataTableReader from a valid DataTable Object:
"DataTableReader is invalid for current DataTable 'TempTable'."
The thing is, if I reboot my machine, it works fine for an undetermined amount of time, then dies with the above. The code that throws this error could have been working fine for hours and then: bang. you get this error.
It's not limited to one line either; it's every single location that a DataTableReader is used. Also, this error does NOT occur on the production web server - ever.
This has been driving me nuts for the best part of a week, and I've failed to find anything on Google that could help (as I'm pretty positive this isn't a coding issue).
Some technical info:
DEV Box:
Vista 32bit (with all current windows updates)
Visual Studio 2008 v9.0.30729.1 SP
dotNet Framework 3.5 SP1
SQL Server:
Microsoft SQL Server 2005 Standard Edition- 9.00.4035.00 (X64)
Windows 2003 64bit (with all current windows updates)
Web Server:
Windows 2003 64bit (with all current windows updates)
Any help, ideas, or advice would be greatly appreciated!
UPDATE 1:
Ok - Have tried the following now with no success:
1: Rebooted
2: SFC / ScanNow
3: Changed SQL Servers
4: Tried a different method that uses DataTableReaders
5: Cleaned solution
The only thing I did find that worked was copy & pasting the code
from the main Visual studio instance, into another which had a simple console app.
This then worked as expected (queried database and got results into a dataTable, created a datatablereader on that table, then queried hasrows before calling .Read()...
All of which worked.
I am struggling to see what could cause this, as there are NO code faults - i'm 100% certain, as it runs perfectly when published to the webserver.
I think using the while(reader.read()) may solve your problem.
if (myReader.HasRows)
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
else
Console.WriteLine("No rows returned.");
myReader.Close();
UPDATE:
Also from msdn:
The HasRows property returns information about the current result set. If the DataTableReader contains multiple result sets, you can examine the value of the HasRows property immediately after you call the NextResult method in order to determine whether the new result set contains rows.
Use the HasRows property to avoid the requirement to call the Read method of the DataTableReader if there are no rows within the current result set.
DataTableReader.HasRows Property
Had the same problem and got rid of it after clearing the variables in the watch window.
Clearing the watch window & doing rebuilds worked for me. However, because I had to remember to frequently rebuild, I eventually just renamed it also. (prior to renaming, adding additional watch variables on an object could cause previous watch variables on that object to become invalid -- even without progressing through the code, ie staying on the same line)
Wrap usage of DataTableReader (and all IDisposables) with using.
OK.. Further down in the code, I have the following code:
using (DataTableReader tr = dtCustomers.CreateDataReader())
{
....
}
If I change this to read:
using (DataTableReader tr2 = dtCustomers.CreateDataReader())
{
....
}
Then, and remember this bit of code is much later down in the same procedure, BOTH bits of code work without fault!
So, this doesn't work:
using (DataTableReader tr = dt.CreateDataReader())
{
...
}
....
using (DataTableReader tr = dt.CreateDataReader())
{
...
}
But this does:
using (DataTableReader tr = dt.CreateDataReader())
{
...
}
....
using (DataTableReader tr2 = dt.CreateDataReader())
{
...
}
I don't understand why this way works, but it does and as I've not had another answer, I'll be going with this.
If you know why this works, and why the original doesn't, please can you enlighten me? :)
Just thought I would post on here in case it's helps someone else. I tried a number of things and in the end i simply changed the name of the datareader and it worked, kind of similar to here. i dont know why for sure but i think it might be because the datareader (originally) wasnt being closed, so maybe after a few times debugging, there was lots of "stuff" in memory with a certain name attached and it said "no more!". still, i could be talking bullpies. my advice, change the name of your datareader variable and make sure you close it after you use it
Seems like a bug on getting the tableReader... i have code that has been working for ears and if i change another method sometimes i get that errro... some times it's solved just recompiling (rebuild), another times i reinstalled the .NET framework or use the option repair of it... i am starting to put try catch sections to use the reader if the system "wants" to givme the reader and the DataTable if not.
Greetings.

LINQ to SQL "1 of 2 Updates failed" on "SubmitChanges()"

I am updating an object of type X and its children Y using LINQ to SQL and then submitting changes and getting this error
Example Code
X objX = _context.X.ToList().Where(x => x.DeletedOn == null).First();
objX.DeletedOn = DateTime.Now;
EntitySet<Y> objYs = objX.Ys;
Y objY = objYs[0];
objY.DeletedOn = DateTime.Now;
_context.SubmitChanges();
On SubmitChanges() I get an exception "1 of 2 Updates failed", no other information as to why that happened. Any ideas?
Also the exception type is
ChangeConflictException
Sooo what was the cause of the problem
- A trigger
I did a sql profiler and saw that
When ObjY's DeletedOn property got updated a trigger updated
ObjX's property (value in table) called CountOfX
which led to an error as the SQL created by LINQ to SQL had the old CountOfX value in it.
Hence the conflict.
If you ever get this error - SQL profiler is the best place to start your investigation
ALSO NOT RELATED TO THE QUESTION
I am testing LINQ to SQL and ADO.net Framework, weirdly this error happened in LINQ to SQL but not in ADO.net framework. But I like LINQ to SQL for its Lazy Loading. Waiting for EF to get outta beta
I'm not sure what the cause of the error may be exactly, but there seem to be a number of problems with the example you've provided.
Using ToList() before the Where() method would cause your context to read the entire table from the DB into memory, convert it to an array; and then in the same line you immediately call Where which will discard the rows you've loaded, but don't need. Why not just:
_context.X.Where(...
The Where method will return multiple items, but the second line in the example doesn't appear to be iterating through each item individually. It appears to be setting the DeletedOn property for the collection itself, but the collection wouldn't have such a property. It should fail right there.
You are using DateTime.Now twice in the code. Not a problem, except that this will produce ever so slightly different date values each time it is called. You should call DateTime.Now once and assign the result to a variable so that everything you use it on gets identical values.
At the point where you have "Y objY = objYs[0]" it will fail if there are no items in the Y collection for any given X. You'd get an index out of bounds exception on the array.
So given this example, I'm not sure if anyone could speculate as to why code modeled after this example might be breaking.
In LINQ2SQL Data Context diagram select the Entity and the field where the count is stored. (A denormalized figure)
Now set the UpdateCheck = Never.
I had this kind of issue. I was debugging running single lines at a time. It turned out another process was modifying this record.
My manual debugging process was slowing down the normal speed of the function. When I ran it all the way to a line after the SubmitChanges method, it succeeded.
My scenario would be less common, but the nature of this error relates to the record becoming superceded by another function/process. In my case it was another process.

Categories