How to set "unchained transaction mode" from entity manager - jpa

I am trying to call a stored procedure using native query call from an entity manager like this
String command = "..."//my stored procedure call command
Query q = getEntityManager().createNativeQuery(command);
But when i run it I got the following message:
Exception, procedure ... can be run
only in unchained transaction mode...
I know if I have a connection object, i can set con.setAutoComit(true) to make this work.
But my question is: since I have a entity manager object, can i set this somehow from entity manager object? I'd like to have the container to manage all the database resources...
I am using EclipseLink.
thanks.
One more note: i don't have the control over the database side,so i cannot go and change the transaction mode to "any".

I found the solution:
getEntityManager().createNativeQuery("set chained off").executeUpdate();

What database/JDBC driver are you using?
Are you using Sybase JConnect? I think it had this issue with some stored procedure calls.
If you cannot fix the issue on the database/drvier, EclipseLink has an option for this.
Using a SessionCustomizer you can set,
session.getLogin().handleTransactionsManuallyForSybaseJConnect();
This will only work if EclipseLink has control of the transactions, not with JTA.

Related

Run an EF core migration without a transaction?

I've got a Postgres database where I use the Postgres type of Enum. The issue I'm having is that when I add an enum via a migration, I get an error stating that it can't be ran in a transaction. This would mean that if I ever had to recreate a database it would always fail because that migration would never run correctly.
So my question is, is there a way of turning off transactions in entity frameworks migrations? Or if you can, whether you would want to?
For clarity, here's a link to the question I've got about the specific failing migration.
ALTER TYPE ... ADD cannot run inside a transaction block - Entity Framework
Thanks
I found that there's an overload for the .Sql command where you can specify true to suppress a transaction.
migrationBuilder.Sql("your sql statement", true);

Accessing DB2-LUW 10 with entity framework 6

I am developing an application in which the database is selected by the end user at runtime. The database can either be on a MS SQL server or an IBM DB2 server. I am currently using IBM DB2 10 Express-c on a windows server for testing. I am developing using Visual Studio 2013 C# and Entity Framework 6. I have installed the EntityFramework.IBM.DB2 Nuget package for the DB2 support. I am using reverse-engineer code-first against an existing SQL server database to generate my base code. The application works fine against a SQL Server database.
I am using System.Data.Common.DbProviderFactories.GetFactory to generate the provider.
System.Data.EntityClient.EntityConnectionStringBuilder connectString = new System.Data.EntityClient.EntityConnectionStringBuilder(a_Connection);
System.Data.Common.DbConnection conn = System.Data.Common.DbProviderFactories.GetFactory(connectString.Provider).CreateConnection();
conn.ConnectionString = connectString.ProviderConnectionString;
LB500Database = new LB402_TestContext(conn, true);
a_Connection is provider=IBM.Data.DB2;provider connection string="Database=LISTBILL;User ID=xxxx;Password=yyyy;Server=db210:50000"
and is being parsed correctly by the EntityConnectionStringBuilder.
I then try to access a table in the database with
LBData500.LB_System oneSystem;
System.Linq.IQueryable<LB_System> allSystem = LB500Database.LB_System.Where(g => g.DatabaseVersion == databaseVersion && g.CompanyID == companyID);
I get an invalid operation exception "Sequence contains no matching element" which means that no elements are returned. If I remove the Where so that all rows are returned (there is one in the table) and try to enumerate the result set using the VS debugger I see the message:
"The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe."
I am not using multi-threading. I am not inside the OnModelCreating.
Just changing the connect string to point to SQL server works fine, so I think my basic approach is sound. If I were getting some kind of error back from the server I would have something to go on. I can run the query from inside Visual Studio, so I have connectivity.
Any pointers would be appreciated.
UPDATE:
I turns out the EF objects were generated using EF5 and the EF6 runtime was being used. I regenerated the EF objects using EF6 reverse engineer code first. I can now connect to the database and get an error message:
"ERROR [42704] [IBM][DB2/NT64] SQL0204N \"DBO.LB_SYSTEM\" is an undefined name."
The schema in the DB2 database is the same as my userid (in this case, not always). I added the CurrentSchema=xxxx to the provide connection string, but EF is still passing dbo as the schema name.
Now I need a way to change the schema name at run time. I saw a link to codeplex EFModelAdapter (http://efmodeladapter.codeplex.com). So I may give that a try.
Update2 After looking through EFModelAdapter, I decided to take a different route. Since I only need database access and not schema management, I decided to go with Dapper (https://github.com/StackExchange/dapper-dot-net). This works great for what I need and allows me to change the schema name when accessing DB2 databases.
As per my Update 2, Entity Framework was a little overkill for what I needed. I switched to dapper https://github.com/StackExchange/dapper-dot-net and I am working fine against multiple DBMSs.

Debugging stored procedure while in use with Entity Framework

I have DocumentItem entity mapped to insert/update/delete stored procedures in Entity Framework edmx.
I'm trying to insert a new Document into the databse along with its DocumentItems. The whole operation is enclosed in a transaction, and it's not easy to debug separately.
This is why I would like to try to debug the sp 'live' - when it's called from entity framework. Is it possible at all?
Just use profiler to see what data EF sends to stored procedure and use that data separately to test / debug only stored procedure. Debugging it together requires you to set debugging session for both .NET code and SQL code and place breakpoint into stored procedure prior to calling SaveChanges on your context. In theory it could work but I never use that.

IDENTITY_INSERT ON not being respected for Entity Framework DBSet.Add method

I run this query:
context.Database.SqlCommand("SET IDENTITY_INSERT [Songs] ON;");
just before I do the .Add() method from a DbSet.
My data still is using the identity value instead of the ID that I'm supplying.
I only want this temporarily (for data migration) and then it should remain auto generated identity in the future.
I'm using SQL Server CE 4 for my database.
This can be a problem. DbContext handles db connection itself. This works only if inserts are executed on the same connection as turning on identity insert. I think it releases the connection after this command. You can try to use different DbContext's constructor and pass your own opened DbConnection instance and handle its closing by yourselves.
EF can't guess that you've executed an IDENTITY_SET command and change its internal logic accordingly.
If you need to insert specific Id values, use SqlCommand for the inserts too.

How to view generated SQL from Entity Framework?

As the title says, how do I view the SQL generated by Entity Framework from within my code? I'm running into an error where the EF is crashing because a field is generated by the database (a DateTime field), and I thought I set it to know that the store is generating it via StoreGeneratedPattern, but it's still crashing, so I would like to see what exactly it's trying to push up to the database.
P.S. I've only been using EF for about an hour now... Switching from L2S.
Since you don't have Sql Profiler, your best choice would be LINQPad. You can use your existing assembly.
Click Add connection -> Use a typed data context from your own assembly -> Entity framework and select your dll.
You can write queries directly against your model (or copy-paste from your code). Select the SQL 'tab' under the query window to view the generated SQL code.
You can use the Entity Framework Profiler (EFProf). It's not free, but there's a 30-day trial available. It does a lot more neat stuff besides showing you the SQL statements.
Generally, you should always use SQL Profiler to see the SQL statements that being submitted by EF into your database.
Also, I think you misunderstood about what StoreGeneratedPattern is. If you look at its possible values inside the model, you'll see that it has identity meaning that the value will be generated (by the database) when the row is inserted and will not otherwise change. The other options are Computed, which specifies that the value will be generated on inserts and updates, and None, which is the default.
So EF will not generate that DateTime field on the fly for you, you need to manually create it and then update your model from database so that EF will generate appropriate metadata to work with it at runtime.
The free AnjLab Sql Profiler will work if real SQL Profiler is not available because you're using SQL Server Express: http://anjlab.com/en/projects/opensource/sqlprofiler. It's not quite as nice as the real thing but it gets the job done well enough.
One solution would be to capture the network traffic and have a look at the data on that level. Microsoft Network Monitor does a good job of this.
Of course, that only works if you're using a separate DB server, and the connection is not encrypted.