How do I clear all the rows from a table using Entity Framework Core? - asp.net-core

New to Entity Framework Core. How do I clear all the rows from a table?
I searched around and found the following solution:
_context.Database.ExecuteSqlCommand("TRUNCATE TABLE[TableName]");
Unfortunately using ExecuteSqlCommand throws a compiler error.
Am I missing a namespace or is there another way to do this?
Thanks, JohnB

ExecuteSqlCommand is Obsolete,you can see the details here.
For the execution of SQL queries using plain strings, use ExecuteSqlRaw instead. For the execution of SQL queries using interpolated string syntax to create parameters, use ExecuteSqlInterpolated instead.
So you can use:
_context.Database.ExecuteSqlRaw("TRUNCATE TABLE[TableName]");

Related

EntityFramework SQLQuery Dynamic Type at Runtime

Im just wondering if there is a way to run a string based SQL query against the dbContext and inspect the objects coming back to give the object a type at runtime. i.e. I will not know the structure of the SQL string being executed until runtime.
Is this possible?
code example:
My_DataProvidor.DB.Database.SqlQuery<MyDynamicType>("SELECT * FROM CUSTOMER").ToList();
OR
My_DataProvidor.DB.Database.SqlQuery(MyDynamicType,"SELECT * FROM CUSTOMER").ToList();
Thanks
Found the answer. Using a micro-ORM framework like Dapper or massive.

How can I programmatically run arbitrary SQL statements against my Hibernate/HSQL database?

I'm looking for a way to programmatically execute arbitrary SQL commands against my DB.
(Hibernate, JPA, HSQL)
Query.createNativeQuery() doesn't work for things like CREATE TABLE.
Doing LOTS of searching, I thought I could use the Hibernate Session.doWork().
By using the deprecated Configuration.buildSesionFactory() seems to show that doWork won't work.
I get "use lacks privilege or object not found" for all the CREATE TABLE statements.
So, what other technique is there for executing arbitratry SQL statements?
There were some notes on using the underlying JDBC Statement, but I haven't figure out how to get a JDBC Connection object from Hibernate to try that.
Note that the hibernate.hbm2ddl.auto=create setting will NOT work for me, as I have ARRAY[] columns which it chokes on.
I don't think there is any problem executing a create table statement with a Hibernate native query. Just make sure to use Query.executeUpdate(), and not Query.list() or Query.uniqueResult().
If it doesn't work, please tell us what happens when you execute it, and join the full stack trace of the exception and the SQL query you're executing.
"use lacks privilege or object not found" in HSQL may mean anything, for example existence of a table with the same name. Error messages in HSQL are completely misleading. Try listing your tables using DatabaseMetadata - you have probably already created the table.

What is the easiest way to find the LINQ statement for a SQL statement

I am a SQL Server DBA for a company that sells an ASP.NET MVC3 application that uses LINQ and Entity Framework 4 for all database access. When I find an inefficient query in my SQL Server's plan cache that was generated by LINQ, I would like to be able to find that LINQ statement in the source code so that I can optimize it. What is the best way to find the LINQ that generated a given SQL statement?
For example, is there any way to put an entry in a config file or decorate the code somehow so that the class and method name or the LINQ statement itself are included as comments in the generated SQL?
The commercial tools ORM Profiler, Entity Framework Profiler or Hugati Query Profiler will both give you a stack trace for the methods which generated the SQL. That makes it fairly easy to find the LINQ in code, though it isn't displayed directly.
These tools also have the advantage that they make it easy to find inefficient queries amongst the many other SQL statements executed by the app.
Although it is not a free tool, this may provide the information you need:
http://efprof.com/
There is also a less expensive tool described here, which I have not used, but it looks very promising:
http://huagati.blogspot.com/2010/06/entity-framework-support-in-huagati.html
http://www.huagati.com/L2SProfiler/
I bet Entity Framework Profiler (http://efprof.com/) would help you out. The workflow is very different from what you asked for (which would be pretty cool BTW). It is a good tool, and is worth a look even if it's not your final solution.
Good luck!
If you have access to the ASP.NET code where the LINQ code is you can more or less know which query you are looking for, copy it into a freeware tool called LINQPad and run it directly there to get the generated SQL statements. http://www.linqpad.net/
You need first get the LINQ queries on your .net code, create a connection to your datasource, paste the Linq code in new queries and run them. You will get the SQL Query generated from the LINQ code.
For example:
from e in ETUSERs
where e.LoginName.Contains("a")
orderby e.LoginName
select e
SQL Results Tab:
-- Region Parameters
DECLARE #p0 VarChar(1000) = '%a%'
-- EndRegion
SELECT [t0].[UserID], [t0].[UsrFirstName], [t0].[UsrLastName], [t0].[LoginName], [t0].[Location], [t0].[Password], [t0].[UsrEmail], ...
FROM [ETUSER] AS [t0]
WHERE [t0].[LoginName] LIKE #p0
ORDER BY [t0].[LoginName]
This is probably not exactly what you are looking for, but it is worth knowing about this tool since it is very helpful to quickly test LINQ queries. There you can quickly edit and run to improve the code without recompiling the whole stuff.
I don't think you can modify the generated SQL easily but what you can do is to get the generated SQL before sending the query to the database.
So you can log every query in a separate textfile with timestamp and source code context information. But that means to modify each place in your source where LINQ queries are sent to the database. Maybe there is an extension point somewhere in the DataContext class for simplifying this.
Anyway here is the code to get the corresponding sql query for a LINQ query:
YourDataContext dc = new YourDataContext();
IQueryable<YourEntityClass> query =
from e in dc.YourEntities
where ...
select e;
string command = dc.GetCommand(query).CommandText;

How can I change column length using HQL query?

I tried session.createSQLQuery("ALTER TABLE People MODIFY address VARCHAR(1000);").executeUpdate();
but this throws org.hibernate.exception.SQLGrammarException: could not execute native bulk manipulation query
After a lot of googling, the recommendation is to use HQL instead of SQL query to do bulk updates. Not sure how to use HQL to accomplish this. There seems to be no decent HQL documentation for updating column length in a table.
Thanks so much for the help.
I suggest you to run this native SQL query via session.connection().
See section 16.2.2.1. Rules/limitations for using stored procedures of Chapter 16. Native SQL, it's near your ALTER query.
All the rest depends on your database vendor. Good Luck!
I could not find a way. Looks like a limitation. I added a new field and copied over data from old field at start-up!

Apply native SQL where clause to Nhibernate query for entity

I have this problem.
I have a module (module 1) that use Nhibernate to manage entity persistence; this module interacs with an other module (module 2).
The "module 2" allows to generate dynamically native SQL where clause. Now I would use it to manage filter operation in "module 1".
Which is the bast way to do it?
Is possible get the native SQL Select from "Nhibernate" entity without write manually it?
Then, if I get the native SQL Select statement I can easily apply where. Is there a better way?
Otherwise, is possible translate navite SQL statement to HQL statement?
i don't exactly understand your problem but it seems to me that filters is what you want
Really I had a old procedure that build where clause and return it in SQL Native Format (according to specific preset)...now to solve my problem I have modified the procedere to obtain the where clause in HQL Format so apply it to my entity. So it works.