how do you get LINQ To SQL Output? - linq-to-sql

if you have a console application, you can do it very easily. You can assign the console output to the context.log
context.log = console.out;
my application is using asp.net mvc3 and linq to sql. I want to see the raw sql statement after it gets translated, so I can improve the performance. how do i monitor the output?

You can do something like this:
var dc = new DataContext(AppSettings.GetConnectionString());
dc.Log = new System.IO.StreamWriter(#"C:\linq.log");
Then just make sure you use that datacontext to get your tables. As soon as that datacontext is used to access the database the SQL will be output to the logfile.

Related

Entity Framework Core Linq query doesn't translate to correct SQL statements

So I am debugging our application which uses Entity Framework Core 2.1.14. I created my entities from database first by scaffolding. Database is MySQL 5.7.29, the SQL data provider for EF Core is Oracle's MySql.Data.EntityFrameworkCore 8.0.19.
Example: a simple Linq query should create a proper SQL statement in the backend. However it does not. "Inactive" is a Byte?.
Dim associates = (From a In DatabaseContext.Associate
Where a.Inactive = 0
Select a.AssociateId).ToList()
This simple Linq query returns: SELECT `a`.`Inactive`, `a`.`AssociateID` FROM `associate` AS `a`. So basically it downloads all associates and does the "where" in memory and returns the values. I know according to the documentation some queries can be complicated and can't be translated, but this is a simplest of the simple queries. Is it because the Inactive column is nullable? Something is terrible not right.
FYI: EF Core is in a class library that is C#. The VB code is in another project that is VB that references the class library.
Hmm, seems the answer is to make the query more specific in VB. I guess the query conversion between C# class library and VB project seems to be the issue.
Dim associates = (From a In DatabaseContext.Associate
Where a.Inactive.Value = Convert.ToByte(0)
Select a.AssociateId).ToList()
This provides the correct query:
SELECT `a`.`AssociateID`
FROM `associate` AS `a`
WHERE `a`.`Inactive` = 0
Very weird that in C# you don't have to check against the .Value and convert the 0 to a byte but in VB I had to do it, there was no other way to get it work. Thanks for everyone trying to help with this.

Is there an Entity Frame Library or extension that handles Json functions with linq?

I would like to complete the following code using Entity Framework in .Net Core to query a JSON object from my API where my API is linked to MS SQL Server 2016. I don't want to take in the entire JSON and query from my backend, I want SQL to handle the querying using the MS JSON Functions and return only the queried information.
Something along the lines of:
var queryList = _context.myTable.Select(r => JSON_QUERY(r.myJsonColumn, '$.info')).ToList();
and
var valueList = _context.myTable.Select(r => JSON_VALUE(r.myJsonColumn, '$.info')).ToList();
I would like to do this without using a string inside the select statement and without creating my own function.
Overall I want a library where I can use JSON_VALUE, JSON_QUERY, ISJSON and JSON_MODIFY with my entity framework and linq.

Getting the raw SQL query string from the ORM

How do I get the raw SQL string sent to the server from the ORM? How do I intercept it in order to do custom work?
I want to forward the query to a custom driver. My target is MS SQL Server via NodeJS - from a Linux environment.
But I don't want to reinvent the wheel. I want to reuse the existing SqlServer query builder.
As long as your query is not executed by toArray() or something similar, you can use $q->sql() to retrieve the raw sql query that cakePHP will execute:
$q = $this->Model->find('all');
$this->log($q->sql()); // log raw sql query
$query = $this->find();
debug($query);
$query is a query object from where you can get the raw SQL expression.

EntityFramework on MySql changing connection string does not change results data

I'm working with EntityFramework 5.0 and MySql. I have generated model from database, and my application now have to connect on multiple database with same structred data.
So i have to dynamic change connection string based on some info.
I try to change database name even from config section of connection string, and with EntityConnectionStringBuilder, but i had the same result: my new connection is stored correctly, but data returned are of the first database.
From WebConfig:
add name="dbIncassiEntities" connectionString="metadata=res:///DAL.Modelincassi.csdl|res:///DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl;provider=Devart.Data.MySql;provider connection string="user id=root ... database=dbname2"" providerName="System.Data.EntityClient" />
From code:
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = "user id=...database=dbname2";
entityBuilder.Metadata = #"res://*/DAL.Modelincassi.csdl|res://*/DAL.Modelincassi.ssdl|res://*/DAL.Modelincassi.msl";
var context = new dbIncassiEntities(entityBuilder.ToString());
My constructor:
public dbIncassiEntities(string conn)
: base(conn)
{
}
What am i missing?
UPDATE
I can see that calling a query directly from SqlQuery, results returned are correct,
while using the generated entities i retrieve wrong data.
var test = context.Database.SqlQuery<string>(
"SELECT cognomenome FROM addetto limit 0,1").ToList();
But calling..
var oAddetto = from c in context.addettoes select c;
So my problem is only on the model itsself, and manually changing the generated schema
<EntitySet Name="addetto" EntityType="dbIncassiModel.Store.addetto" store:Type="Tables" Schema="dbname2" />
..i'll get the right information.
My question now is: how can i change in code these informations??
Any help is really appreciated!!
Thanks, David
Ok, i've found a workaround for now.
I simply clear the shema name on the designer, and now i can call the generated entities succesfully. Hope this can help anyone else.
David
While I could not remove the Schema in the designer, I removed it directly in the .edmx file. Do a full text search for Schema="YourSchema" in an XML editor of your choice and remove the entries. After that, changing the connection string is enough.
Downside is, the Visual Studio designer and mapping explorer won't work properly anymore.
This seems to be more of a dotConnect issue rather than MySQL, since the problem also exists for the Oracle adapter:
http://forums.devart.com/viewtopic.php?t=17427

Linq to SQL and SQL Server Compact Error: "There was an error parsing the query."

I created a SQL server compact database (MyDatabase.sdf), and populated it with some data. I then ran SQLMetal.exe and generated a linq to sql class (MyDatabase.mdf)
Now I'm trying to select all records from a table with a relatively straightforward select, and I get the error:
"There was an error parsing the query. [ Token line number = 3,Token line offset = 67,Token in error = MAX]"
Here is my select code:
public IEnumerable<Item> ListItems()
{
MyDatabase db_m = new MyDatabase("c:\mydatabase.sdf");
return this.db_m.TestTable.Select(test => new Item()
{
ID = test.ID,
Name = test.Name,
RequestData = test.RequestData != null ? test.RequestData.ToString() : null,
Url = new System.Uri(test.Uri)
}.AsEnumerable();
}
I've read that Linq to SQL works with Sql Compact, is there some other configuration I need to do?
Could it be an errant NVARCHAR(MAX)? I think I've seen an error like this before with sql compact edition, and as I recall it had to do with the fact that sql compact edition doesn't support the NVARCHAR(MAX) datatype. This is also maybe why you see the "token in error = MAX" message in the exception?
Why do you need to do the conversion on RequestData? What does your class look like? Can you just set it like this?
RequestData = test.RequestData
I also tried the approach of using a SQLMetal for a SQL Server compact edition in a Winforms app for Linq-to-sql
.
After some problems i skipped the Linq-to-SQL Approach and went for the Linq-To-Entities approach. The syntax is like 99% the same for the query's i'm doing so ;-)
Also, when using the edmx designer, it's possible to easy update , delete and add tables.(with drag drop or Right-Click equivalent in the designer.)