string length failing in Azure using LINQ - c#

I having issues with SQL Azure, the following LINQ with EF code works fine if the database is SQL Server 2012
var userLength = users.Select(n => new { n.FirstName.Length });
But, if I point it to an Azure database and I get
"base = {"The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."}"
Any ideas?

Do the databases contain same data?
Maybe one of users has no FirstName set in Azure database?
I guess it's when you iterate over usersLength that you receive this Exception? Is it thrown on first iteration or maybe later?
Here's what I think is happenning (I'm using LINQ to Objects here)
You can edit it like this to make it return 0 for null elements (FirstNames):
You can download those two code snippets if you have LinqPad here (they will be automatically opened in LinqPad):
http://share.linqpad.net/2pfjqf.linq
http://share.linqpad.net/vp96kf.linq

Related

Select Numeric Values From String Linq to Entities

I have records that have a string property called Project. The values these normally have are like A-A-40019-0 but in reality they could be anything.
I need to be able to extract the numeric values from the Project project property so that I can then try and cast it to a ulong so that it can be sorted by.
I'm trying the following code to select the number values from the Project property.
return jobs.Select(x => new JobViewModel
{
Sequence = x.Project.Where(y => char.IsDigit(y)).ToString()
});
When I try this I get the following error
DbExpressionBinding requires an input expression with a collection
ResultType.
I need to use Linq to Entities as I can't afford to load all records into memory.
I'm using SQL Server.
You don't say which DB you are using but I did find this for SQL Server. https://www.mytecbits.com/microsoft/sql-server/extract-numbers-from-string#:~:text=%20Extract%20Numbers%20From%20String%20In%20SQL%20Server,you%20want%20to%20split%20this%20delimited...%20More%20
Hopefully similar technique can be used for the DB you are using.
You could make a view with a column calling that function added on the end and then you can sort it.
or purely in C# which I haven't tried:
Convert.ToInt32(new string(y.project.Where(c => Char.IsDigit(c)).ToArray())

Dynamic LINQ query - passing string issue

I have a column named Rule in DB for storing one line of c# code, I want to retrieve them to.net program. The problem is, the retrieved line by lambda expression is not recognizable by .net program because of the c# class name in it. So is that the dynamical linq limit which can't implement it or not?
Expample 1:
Retrieved string from DB:
Regex.IsMatch(string.Concat(fieldValue1.Where(q => !Path.GetInvalidFileNameChars().Contains(q))), #"\d{11}")
Lambda Expr consuming the above retrieved string:
var result = fieldInfo.Where(RetrievedstringfromDB, Value)
The error is
No property or field 'Regex' exists in type 'XXX'
The closest thing I found that would do that is using Roslyn to run the whole thing dynamically, but to be fair that might not a good workaround for the project I am working on now, any lights/thoughts would be much appreciated!

Dapper throws exception second time you run a query if different results schema

I'm using Dapper, Sqlite on c# coreclr.
public async Task<UserPoco> GetFromEmail(string email)
{
email = email.ToLower();
using (var connection = new SqliteConnection(_configSettings.ConnectionString))
{
connection.Open();
var query = $"SELECT * FROM users WHERE EmailAddress = '{email}';";
var result = await connection.QueryAsync<UserPoco>(query);
return result.FirstOrDefault();
}
}
That simple method throws an exception if at some point the SQL query find no results and next time it runs it does find results.
It throws:
Unable to cast object of type 'System.Int64' to type 'System.Int32'.
Error parsing column 0 (UserId=86 - Int64)
I'm pretty sure it's not related to the Datatypes. The UserPoco has a long UserId property and the DB table users has a UserId of type INTEGER which is the recommended one to store bigint (long). Moreover, for example if the method always finds data it will work like a charm.
I do think is related to the fact that Dapper caches the result schema of every query it runs and throws an exception when this schema changes for the same query as they point out on:
https://github.com/janjosephlim/dapper-dot-net/issues/124
What I don't understand is how come I can't find more info about this or more people is complaining about such a common scenario: I'm just running a very simple query multiple times which can bring back or not results.
What am I missing?
I don't know why sqlite is misreporting the data type, but: the data type checks have been improved in recent pre-release builds. Please check with the latest pre-release build: I expect it is already fixed.

SingleResult<myObject> .ToList or .Count throws an InvalidCastException

I have a stored procedure GetTopRecords(). The sp returns the top 500 records.
I dragged the sp from the server explorer to the LinqtoSql designer surface.
I changed the return type to Record
In code I have:
var x = myDataContext.GetTopRecords();
var y = x.Count();
var z = x.ToList();
either one of the last two lines above throws an InvalidCastException
the type of x is
System.Data.Linq.SqlClient.SqlProvider.SingleResult<Record>
Why am I getting an exception? What am I doing wrong? Please help.
x is not a list, it is single element. As a single element you can't convert it to a list of more than one element or count how many elements it has.
As you say "I changed the return type to Record". Why did you do this?
Since this is L2S (Linq To SQL), I'm assuming it's using Lazy loading, which means that only when calling Count or ToList, which are of immediate execution, the query is performed.
That said, the problem should be related to what you are returning from the GetTopRecords method, which isn't compatible with the Record type.
You should use the L2S designer to check if the result of that method is correctly mapped to a Record data type. Meaning that Record should be a L2S mapped table and GetTopRecords should return data from that table.
Well,can you give details what GetTopRecords() .What it returns?do you need count of top records?
var x = i.ToList();
var y = x.Count();
then it will allowed,but when ever you use tolist() ToList iterates on the query and creates an instance of List<> initialized with all the results of the query.
which is same for count(),becuse count also need all records to perform counting.
the purpose of tolist is to prefilled data with result.
I think there there have been changes to the database schema since the linq to sql classes were generated. therefore there is a mismatch between the database table and the linq to Sql object representing it. therefore, the calls fail because the .NET cannot successfully cast from the db created object to the linq to sql object
I am not sure how I resolved this. But it is fixed now. If someone runs into this problem, please add a note here and I will look up my code and post the proper answer. While I thank the responders above, unfortunately, none of the answers above helped.

LINQ to Entities: Query not working with certain parameter value

I have a very strange problem with a LINQ to Entities query with EF1.
I have a method with a simple query:
public DateTime GetLastSuccessfulRun(string job)
{
var entities = GetEntities();
var query = from jr in entities.JOBRUNS
where jr.JOB_NAME == job && jr.JOB_INFO == "SUCCESS"
orderby jr.JOB_END descending
select jr.JOB_END;
var result = query.ToList().FirstOrDefault();
return result.HasValue ? result.Value : default(DateTime);
}
The method GetEntities returns an instance of a class that is derived from System.Data.Objects.ObjectContext and has automatically been created by the EF designer when I imported the schema of the database.
The query worked just fine for the last 15 or 16 months. And it still runs fine on our test system. In the live system however, there is a strange problem: Depending on the value of the parameter job, it returns the correct results or an empty result set, although there is data it should return.
Anyone ever had a strange case like that? Any ideas what could be the problem?
Some more info:
The database we query against is a Oracle 10g, we are using an enhanced version of the OracleEFProvider v0.2a.
The SQl statement that is returned by ToTraceString works just fine when executed directly via SQL Developer, even with the same parameter that is causing the problem in the LINQ query.
The following also returns the correct result:
entities.JOBRUNS.ToList().Where(x => x.JOB_NAME == job && x.JOB_INFO == "SUCCESS").Count();
The difference here is the call to ToList on the table before applying the where clause. This means two things:
The data is in the database and it is correct.
The problem seems to be the query including the where clause when executed by the EF Provider.
What really stuns me is, that this is a live system and the problem occurred without any changes to the database or the program. One call to that method returned the correct result and the next call five minutes later returned the wrong result. And since then, it only returns the wrong results.
Any hints, suggestions, ideas etc. are welcome, never mind, how far-fetched they seem! Please post them as answers, so I can vote on them, just for the fact for reading my lengthy question and bothering thinking about that strange problem... ;-)
First of all remove ObjectContext caching. Object context internally uses UnitOfWork and IdentityMap patterns. This can have big impact on queries.

Categories

Resources