C# Retrieve / Get SQL statement from Linq - linq

How can I retrieve the SQL statement from below code in C#.net?
Customer _obj = new Customer();
db = new LinqDataContext();
_obj.name = "name";
db.Customers.InsertOnSubmit(_obj);
db.Customers.Context.SubmitChanges();

You can use the Log property of DataContext object. Also, it depends on the type of application you are using.
For Web Application:-
db.Log = Response.Output;
For Console Application:-
db.Log = Console.Out;
Apart from this you can also use the GetCommand method of DataContext class. Sql Server Profiler is again an obvious option.

Use sql profile like this one https://expressprofiler.codeplex.com/
where you can see the generated sql.

You need to use SQL Profiler on database, it will give you exact query run by EF on DB.
http://msdn.microsoft.com/en-IN/library/ms181091.aspx
https://expressprofiler.codeplex.com/

Related

Multiple entity framework 6 contexts in oracle throw ORA-00955

I am using Entity Framework 6.1.3 connecting to an oracle database.
I am trying to use multiple contexts with the same schemaName for oracle. But when I create the contexts it appears they share the __MigrationHistory table and when the second context attempts to create itself it throws "ORA-00955: name is already used by an existing object". To be clear the two contexts I attempted to split by domain design and do not share any entities between the two.
This is the code I'm attempting to run, and it works fine when I run it against SQL Server. But Oracle throws the ORA-00955 error.
try
{
using (var hContext = new HContextORCL(connectionString, "SchemaName"))
using (var aContext = new AContextORCL(connectionString, "SchemaName"))
{
hContext.Database.Initialize(true);
aContext.Database.Initialize(true);
}
}
I've tried using CreateIfNotExists() instead of the Initialize but receive the same error. I have tried setting both contexts Database.SetInitializer<context>(null); because I don't need the migrations at this point. But that doesn't seem to work either.
Ideally I would like to keep the __MigrationHistory table and have both my contexts initialized in Oracle. But that's not necessary. I can sense myself going off the rails trying to figure out all these work-arounds which when I look at them seem overly complicated for something that works in SQL Server.
I am at a loss how to intialize two contexts with the same schema name in an oracle database.
Alright, for better or worse this is the work around I'm going with. My issue appears to be the MigrationHistory table is shared between the two contexts.
Entity Framework 6 allows you to manipulate the migration table using the System.Data.Entity.Migrations.History namespace (Migrations.History Namespace).
So I open the migrations table, copy all the history rows out, delete the migration table, perform my second context initialization and copy the history rows back into the migration database (created during the second context initialization).
try
{
var dbConnection = new OracleConnection(connectionString);
using (var migrationContext = new Migrations.History.HistoryContext(dbConnection, "SchemaName"))
using (var hContext = new HContextORCL(connectionString, "SchemaName"))
using (var aContext = new AContextORCL(connectionString, "SchemaName"))
{
hContext.Database.Initialize(true);
List<HistoryRow> currentHistory = migrationContext.History.ToList();
migrationContext.Database.Delete();
aContext.Database.Initialize(true);
currentHistory.ForEach(rowItem => migrationContext.History.Add(rowItem));
migrationContext.SaveChanges();
}
}

Database specific queries in a Spring Hibernate application

In a dao class implementation,I want to use different sql query depending upon the underlying database. Since my SQL query is complex which selects from a database view and uses "UNION" key word and uses database specific functions, I can not use JPQL (or HQL). I did some search on Stackoverflow and threads suggest the good way would be to find out the dialect used in the application. Can anyone provide some code example?
EDIT : My apologies, I did not explain my question well enough. In my dao class implementation , I want to determine the database ( say mysql or oracle) on which my application is running and then execute the appropriate query. I need the code like jdbcTemplate.findOutTheDialect().
JPA have the native queries for that.
An example you can find here.
You can use spring JdbcTemplate to connect and query from your database.
For Example..
String query = "SELECT COUNTRY_NAME FROM COUNTRY WHERE MCC_COUNTRY NOT IN ('Reserved') ORDER BY COUNTRY_NAME";
jdbcTemplate.query(query, new ObjectRowMapper());
Where "ObjectRowMapper" will be a class to map return resultset to list of Objects.

Does Entity Framework automatically load all of my data (not a reference and lazy load is off)?

I have a database first Entity Framework project. For every entity that I add, a collection is added to the DbContext for the entity. I explicity set LazyLoadingEnabled = false in the DbContext constructor. If I break into the following code and check the count of CustomerDepartments, I get the total count of the table. If I'm just adding a new record, I expect the count to be 0 before I add, and 1 after. I'm using this in a stateless environment, so loading the whole table just to add a record seems absurd. What am I doing wrong?
using (Model.SupportEntities support = new Model.SupportEntities(_state.Credentials, _handler.ReadWriteConnectionString))
{
Model.CustomerDepartment department = Json.JsonConvert.DeserializeObject<Model.CustomerDepartment>(_insertObject);
support.CustomerDepartments.Add(department);
support.SaveChanges();
_state.ReturnNewIdAsJson(department.CustomerDepartmentID);
}
It seems you have misinterpreted how DbContext and DbSet works.
It maybe best if you get hold of a tool for logging EntityFramework SQL calls try Clutch.Diagnostics.EntityFramework.
When you call IEnumerable<T>.Count() on DbSet<T>, Entity Framework runs the following query
SELECT COUNT(*) FROM TableName;
But it does not load the whole table.
The ACTUAL call you want for the behavior you wanted was either
support.CustomerDepartments.Local.Count;
OR
support.ChangeTracker.Entries<T>().Count()
These will NOT hit the database.
You have to remember that DbSet is an abstraction for the Database table, so calling Count() on it should tell you how many rows there are in the table.
BTW. FYI. The convention is call name your DbContext to be SupportContext. Model named classes or namespace suggests they are your POCOs.

Linq to Crm (2011) Trouble searching by username for systemuser

I have a win app that is using linq to crm to query a system user by username
in Crm 2011(IFD). I have the following code snippet which shows what I am trying
to accomplish. The method executes without error, however no records are found.
The username appears as "domain\testuser" om CRM.
public static SystemUser LookUpSystemUser()
{
var username= "domain\\testuser");
var list = (from c in Context.CreateQuery<SystemUser>()
where c.DomainName.Equals(username)
select c).ToList();
return list.FirstOrDefault();
}
Recreating the application seemed to fix the problem. There are still no code differences, so still unsure what happened.
This really isn't an answer to your question, and in your particular instance it really won't matter due to there only being one SystemUser per DomainName, but it is a best practice.
When calling ToList() on your LINQ statement, it will return all entities from the SQL database that match the query. Then calling FirstOrDefault() will return the first, client side.
Instead of calling ToList() when only interested in one, call FirstOrDefault(). This will actually result in Top 1 added to the select query. This will result in less resources being consumed on the SQL server, CRM Webserver, and data being transfered between the SQL server, the CRM Webserver, and the client.
Try to run this method (or a canonical equivalent of it) and see if you get anything at all. If so, you can then tighten up the condition in Select statement.
public static SystemUser LookUpSystemUser()
{
return Context.CreateQuery<SystemUser>()
.Select(element => true)
.FirstOrDefault();
}
Remember that default(SystemUser) will produce null.
Not at the computer, haven't tested it.

Entity Framework get entity via variable

I have a listbox populated with table names. I want to be able to click a row in the listbox and return all records from that table and bind to a datagridview. Using good old fashioned SQL this is a piece of cake. Attempting to do the same with Entity Framework 4.3.1 is another matter.
For instance, is there a way to represent "get_picklist_names_v" as a variable in this code below?
static class EfHelper
{
public static EfEntities CreateContext()
{
EfEntities context = new EfEntities();
return context;
}
}
using (var context = EfHelper.CreateContext())
{
IList list = context.get_picklist_names_v.ToList();
lboPicklist.DataSource = list;
lboPicklist.DisplayMember = "name";
}
Entity Framework abstact the SQL stuff with types and does its best so you don't have to write sql for each server flavor (Oracle, SQL Server, MySQL, etc.). That's what an ORM does...
If your used to generic types its quite trivial to do the same with Entity Framework.
It's not exactly what yor looking for but maybe you can find some hints from the followig article :
Repository Pattern with Entity Framework
Entity Framework is not the best tool to achieve this. You could try Entity Sql, but the problem is that in order to use that in a dynamic way you have to capture the results in an IEnumerable<DbDataRecord>. A DataGridView won't display that as such.
There is nothing more convenient for this than filling a DataSet by a TableAdapter and a sql statement. I would stick to that if I were you.

Resources