Sample for Entity Framework 6 + Code First + Oracle 12c - entity-framework

I have a problem with a Visual Studio solution using Entity Framework 6 + Code First + Oracle 12c. I'm not sure it is properly configured, or if I missed something simple.
I tried to look for a sample project as a start, but was not able to find - google search, stackoverflow etc.
Is there a minimalistic sample project somewhere, which tries to create the database when runs?
Update: Just to make sure, I'm not asking anyone to create a sample for me. Before I'll do it, I want to make sure there is really no existing sample (which is strange for me, but very well might be the case).

I managed to create a working sample. Found some (not so) documented strange behaviors resulting in run time errors along the way.
Here is the full sample source: https://drive.google.com/file/d/0By3P-kPOnpiGRnc0OG5ZTDl6eGs/view?usp=sharing&resourcekey=0-ecT1EU81wJOQWokVDr_r9w
I created the sample with Visual Studio 2013. Used nuget to pull
EntityFramework 6.1.3
Official Oracle ODP.NET, Managed Entity Framework Driver 12.1.021
The important parts are
Program.cs
Context.cs
TestEntity.cs
App.config
I omit
packages.config
AssemblyInfo.cs
csproj, sln files
I also omit namespaces.
using System.Data.Entity;
public class Program
{
private static void Main(string[] args)
{
string connStr =
"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=***server***)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=***SERVICE***)));Persist Security Info=True;User ID=***User***;Password=***password***";
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Context>());
//Database.SetInitializer(new DropCreateDatabaseAlways<Context>());
Context context = new Context(connStr);
TestEntity te = new TestEntity();
te.Id = 1;
te.Name = "Test1";
context.TestEntities.Add(te);
context.SaveChanges();
}
}
using System.Data.Entity;
public class Context : DbContext
{
public Context(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public virtual DbSet<TestEntity> TestEntities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("OTS_TEST_EF");
modelBuilder.Entity<TestEntity>()
.Property(e => e.Id)
.HasPrecision(9, 2);
base.OnModelCreating(modelBuilder);
}
}
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("TestEntity")]
public class TestEntity
{
[Column(TypeName = "number")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public decimal Id { get; set; }
[StringLength(100)]
public string Name { get; set; }
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false"/>
<section name="oracle.manageddataaccess.client"
type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<entityFramework>
<!--<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>-->
<providers>
<!--<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>-->
<provider invariantName="Oracle.ManagedDataAccess.Client"
type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.ManagedDataAccess.Client"/>
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver"
type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<publisherPolicy apply="no"/>
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral"/>
<bindingRedirect oldVersion="4.121.0.0 - 4.65535.65535.65535" newVersion="4.121.2.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<!--<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=INFOTEST))) "/>
</dataSources>
</version>
</oracle.manageddataaccess.client>-->
<!--<connectionStrings>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client"
connectionString="Data Source=(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = INFOTEST)));Persist Security Info=True;User ID=user;Password=password"/>
</connectionStrings>-->
</configuration>
The strange thing I found on the way:
Adding any of the following TypeNames will result in "Sequence contains no matching element" error.
/*[Column(TypeName = "numeric")]*/
/*[Column(TypeName = "number(18,0)")]*/
/*[Column(TypeName = "number(18,2)")]*/
Indicating precision with scale 0
modelBuilder.Entity<TestEntity>().Property(e => e.Id).HasPrecision(9, 0);
Will result in
Schema specified is not valid. Errors:
(7,12) : error 2019: Member Mapping specified is not valid. The type 'Edm.Decimal[Nullable=False,DefaultValue=,Precision=9,Scale=0]' of member 'Id' in type 'EF6_Oracle12c_CF.TestEntity' is not compatible with 'OracleEFProvider.number
Omitting the
modelBuilder.HasDefaultSchema("OTS_TEST_EF");
line will result in
ORA-01918: user does not exists
It is also happened that I got
ORA-00955: name is already being used by existing object
or
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
I managed to overcome those by enabling the
Database.SetInitializer(new DropCreateDatabaseAlways<Context>());
line, instead of the DropCreateDatabaseIfModelChanges mode.

This has the a good sample if you are still interested . It is available on 11 g .
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/CodeFirst/index.html

Here's a link to a sample from Oracle on using EF Code First, Migration and Visual Studio.
Oracle Learning Library on EF Code First and Code First Migration
I'm actually almost finishing up a project that uses VS, 12c and EF and the link was a good starting point. There was no particular issue about 12c that I saw.

I have a test project on github that I used to try out examples of EF6 migrations on Oracle. The code that works for me (to programatically execute all pending migrations) is here. My use case is likely common - I need to be able to deploy my application to various environments and data centres and have it do "the right thing" to work with the environment's copy of my application database.
The important bit is
//Arrange
Configuration config = new Configuration();
DbMigrator migrator = new DbMigrator(config);
Console.WriteLine("Migrating...");
foreach (string s in migrator.GetPendingMigrations())
{
//Act
Console.WriteLine("Applying migration {0}", s);
Action act = () => migrator.Update(s);
//Assert
act.ShouldNotThrow();
}

I spent days fixing this issue... Finally I solved it:
The table did not exist. I checked many times and refreshed, but the problem was not in the table itself, it was with the sequence. Every table in Oracle creates a sequence object to increase the id. So, if you delete the table make sure to drop the sequence as well, otherwise when you migrate again, it will give you ORA-00955: name is already used by an existing object.
So, the real problem is in the sequence, not in the table. But you cannot create new sequence because it already exists. It is not deleted when you delete the table, it should be deleted manually.
I hope this will help someone.

Related

Resolving connection string in EFv6.3 in ASP.NET Core Windows service project

I have an ASP.NET Core application running as a Windows Service. Due to project requirements, I am using Entity Framework v6.3 (as opposed to using EF Core).
I am having trouble retrieving the correct connection string when performing a migration and also upon publishing the service to a server. When running the service locally, the connection string is retrieved successfully.
As I understand it, Entity Framework 6 is supposed to retrieve connection strings from web.config or app.config files, right? Therefore, I have an app.config file containing two connection strings, e.g.
<connectionStrings>
<add name="DataContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
<add name="CrmContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
</connectionStrings>
In my Startup class, I have registered both database contexts, e.g.
services.AddTransient<DataContext>();
services.AddTransient<CrmContext>();
On a Razor page, when I instantiate both data contexts on my local machine I can see the correct connection string is being resolved for both contexts (by using _crmContext.Database.Connection.ConnectionString).
When I attempt to add a migration using the update-database command on my CrmContext (automatic migrations enabled), the correct connection string isn't resolved. Instead, it defaults to creating a LocalDB database using the default connection string: (localdb)\MSSQLLocalDB
How come it isn't using the connection string I have provided in my app.config file? I also a web.config file but it doesn't resolve from there either.
CrmContext.cs
public class CrmContext : DbContext
{
public CrmContext() : base("CrmContext")
{
Database.SetInitializer<CrmContext>(null);
}
public IDbSet<CustomerDetails> CustomerDetails { get; set; }
}
CrmConfiguration.cs
internal sealed class CrmConfiguration : DbMigrationsConfiguration<CrmContext>
{
public CrmConfiguration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(CrmContext context)
{
...
context.SaveChanges();
}
}
I've tried to explicitly update the CRM connection by specifying my CrmConfiguration file:
update-database -ConfigurationTypeName CrmContext
When I do this, it creates and updates the LocalDB database instead of using my connection string.
I've also tried to explicitly referencing the connection string:
update-database -ConnectionStringName "CrmContext"
This results in this error:
No connection string named 'CrmContext' could be found in the
application config file.
My CrmContext class exists within my ASP.NET Core windows application where my DataContext class exists in a separate 'Data' project (as it's shared with an ASP.NET MVC v5 application)
When I publish my service and install the application as a Windows Service, I found that it also doesn't pick up the connection strings at all from any of the config files - it again just looks for the default localdb database. As I understand, it should pick it up from my PaymentBatchProcessorService.exe.config file, right?
My PaymentBatchProcessorService.exe.config file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DataContext" providerName="System.Data.SqlClient" connectionString="redacted" />
<add name="CrmContext" providerName="System.Data.SqlClient" connectionString="redacted" />
</connectionStrings>
</configuration>
As per Microsoft documentation, it should be possible to load in the additional XML configuration files via the following code in the Program.cs file, but EntityFramework still didn't pick up the connection strings:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostingContext, config) =>
{
var workingDirectoryPath = Environment.GetEnvironmentVariable(EnvironmentVariables.ServiceWorkingDirectory);
config.AddXmlFile(Path.Combine(workingDirectoryPath, "app.config"));
config.AddXmlFile(Path.Combine(workingDirectoryPath, "web.config"));
})
e.g. in the above sample, the working directory path resolves to the location where my .exe is for the Windows Service.
Thanks for reading this far!
When you deploy your service, the .config file should instead be called servicename.exe.config. It should reside on the same folder where the service was registered with installutil. See Windows service app.config location.

Azure Api/Web App with Entity Framework - SQL database connection string

I'm adding an SQL database to my Azure API App. I have an empty SQL database which I created separately via portal.azure.com. My problem is I don't know how to set up the connection string so that my app uses the Azure database.
I have followed the Code First Migrations article, but I'm stuck on the deployment phase. I cannot see any connection configuration in any of the files in the project.
How do I set the connectionString to be used by the app when it's deployed in Azure?
More info:
To be precise, I can see 2 things:
Commented out connectionStrings sections in Web.Debug/Release.config files.
Some EF configuration in Web.Config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
(...)
When I execute tests locally I can see Database.Connection.ConnectionString is
Data Source=(localdb)\mssqllocaldb;Initial Catalog=XDataAPI.Models.MyContext;Integrated Security=True;MultipleActiveResultSets=True
BTW. The publish window states that no database have been found in the project. (This doesn't really bother me, it's a secondary issue)
Edit:
DbContext, as requested:
public class MyAppContext : DbContext
{
public DbSet<Organisation> Organisations { get; set; }
}
Pass in the connection name as param to your constructor, and then use the same connection name when setting up your connection string in your web.config, like this:
public class MyAppContext : DbContext
{
public MyAppContext():base("MyConnectionName"){}
public DbSet<Organisation> Organisations { get; set; }
}
And then, in web.config:
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="MyConnectionName" connectionString="Server=tcp:test.database.windows.net,1433;Database=testdb;User ID=test#test;Password=p4ssw0rd!;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
<configuration>
If you want to run from a local machine, remember that you need to allow incoming connections from your IP on your Azure database server firewall.
If you set up the SQL Server VM, then
<add name="DataContext" connectionString="Data Source=VMname.cloudapp.net; Initial Catalog=catalog; User ID=login;Password=password; MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
If you set up the SQL Azure, then that tutorial should be used.
As for the connection string place, please refer to some documentation. You use LocalDB, instead of that you should use the SQL Server.
You should be able to just update the connection string for your data context in the web.config to use you Azure SQL Database. For my testproject it is just at the top of web.config:
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="WebApplication4Context" connectionString="Server=tcp:test.database.windows.net,1433;Database=testdb;User ID=test#test;Password=p4ssw0rd!;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
<configuration>
Don't forget to also update the firewall settings of your Azure SQL Database Server to make it accessible for your application.
Edit: You can also change the database connection for just your Azure environment by adding the your Azure SQL DB in the Publish dialogue:
If the connection string is missing web.config, then it is using the default name which is DefaultConnection and it refers to the localdb instance that gets installed with SQL or SQL Express.
To configure it, you have to first create a SQL DB on Azure, from the Portal, create a new database and give it a name and make sure it exist in the same resource group and region to decrease the latency and improve the performance.
Open the created database and you will find the connection string for many platforms, copy the one for .Net and go to the Web App settings, you should find a place for connection strings, add a new one and name it DefaultConnection and add the value a the connection string you just copied from the database blade
When you run the application for the first time, code first will connect to the database and apply the migration if you specified that during the publish wizard which adds some configuration in web.config as well.
For .Net FW 4.5 or above:
1. Your DbContext class:
public class MyAppContext: DbContext
{
public MyAppContext() : base("YourConnectionStringKey") { }
public DbSet<Organization> Organizations{ get; set; }
}
2. Your Web.config:
<connectionStrings>
<add name="YourConnectionStringKey" connectionString="DummyValue" providerName="System.Data.SqlClient" />
</connectionStrings>
3. In your Azure WebApp settings, add the connection string (which will be automatically injected into your Web.config at runtime)
If you're not developing using the .Net framework, see https://azure.microsoft.com/en-us/blog/windows-azure-web-sites-how-application-strings-and-connection-strings-work/ for further details.

Microsoft.Practices.EnterpriseLibrary.Data.DLL but was not handled in user code

Searched google and using Enterprise library data access to connect database.
Installed only data access pack using https://www.nuget.org/packages/EnterpriseLibrary.Data/.
After added to the project, I've set the configuration as follows,
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
</configSections>
<dataConfiguration defaultDatabase="dProvider" />
<connectionStrings>
<add name="dProvider" connectionString="server=local;Initial Catalog=n;uid=sa;pwd=pwd"
providerName="System.Data.SqlClient" />
</connectionStrings>
Called through the application like the following,
Database db;
string sqlCommand;
DbCommand dbCommand;
db = DatabaseFactory.CreateDatabase("dProvider"); or DatabaseFactory.CreateDatabase();
After run the application, I got the following exception,
{"Database provider factory not set for the static DatabaseFactory. Set a provider factory invoking the DatabaseFactory.SetProviderFactory method or by specifying custom mappings by calling the DatabaseFactory.SetDatabases method."}
What mistake I made ? How to solve this issue ?
Finally found the answer. It has been occurred because of the configuration section.
I've used version 6, but here I've mentioned like version 5 in the configuration section. So the error has occurred.
I've replaced the configuration section like following, It worked perfectly in good way. :-). Thanks a lot for the helpers.
<configSections>
<section name="dataConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
Microsoft.Practices.EnterpriseLibrary.Data"/>
</configSections>
and used DataBaseProviderFactory class to create instance.
DatabaseProviderFactory factory = new DatabaseProviderFactory();
db = factory.Create("dProvider");

Entity framework 6 without config file?

I have an application that can not use a config file and has to set up the connectionstring for the entity context by code (with EntityConnectionStringBuilder).
The problem comes however with this:
No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'.
Since I can not use the standard app.config file, am I screwed in EF6? It was not a problem in EF4 if I recall correctly.
So the settings inside the entityFramework-tag is something I wish to set in code.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
I'm using EF 6 without an App.config file at all I just pass a connection string to my DBContext (well the connection is read out of a config file elsewhere but that's up to you). Just Remove all the EF stuff from the config file.
Here's how I got it to work.
public partial class MyDbContext : DbContext, IMyDbContext
{
public MyDbContext(string connectionString,
DbValidationMode validationMode = DbValidationMode.Enabled,
DbLazyLoadingMode lazyLoadingMode = DbLazyLoadingMode.Disabled,
DbAutoDetectMode autoDetectMode = DbAutoDetectMode.Enabled)
: base(((EntityConnectionStringBuilder)new EntityConnectionStringBuilder()
{
Provider = "System.Data.SqlClient",
ProviderConnectionString = connectionString,
Metadata = #"res://*/Contexts.Test.MyModel.csdl|res://*/Contexts.Test.MyModel.ssdl|res://*/Contexts.Test.MyModel.msl"
}).ToString())
{
this.Configuration.ValidateOnSaveEnabled = validationMode.Equals(DbValidationMode.Enabled);
this.Configuration.LazyLoadingEnabled = lazyLoadingMode.Equals(DbLazyLoadingMode.Enabled);
this.Configuration.AutoDetectChangesEnabled = autoDetectMode.Equals(DbAutoDetectMode.Enabled);
}
... Etc
Then I just inject this context into all my services.
I'm using Database First design so I found it easier to modify the T4 Templates.
There may be nicer ways of doing this but I've not ran into any problems at all.
In EF6 you can use Code-based Configuration for Entity Framework specific setup. (Also see How to add entity framework 6 provider in code?). Then you can build connection string and pass it to the ctor of the context.

Setup of mvc-mini-profiler for EF-db- first

I'm trying to use the mini-profiler with old-style EF code - database-first.
So far:
I've created a db context using:
string connectionString = GetConnectionString();
var connection = new EntityConnection(connectionString);
var profiledConnection = ProfiledDbConnection.Get(connection);
_context = profiledConnection.CreateObjectContext<MyEntitiesType>();
but then I hit a "Unable to find the requested .Net Framework Data Provider. It may not be installed."
which I worked around using a <system.data> reference to the MvcMiniProfiler provider:
<system.data>
<DbProviderFactories>
<remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
<add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider" description="MvcMiniProfiler.Data.ProfiledDbProvider" type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler" />
</DbProviderFactories>
</system.data>
but now I'm hitting a stack overflow somewhere in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\Data\ProfiledDbProviderServices.cs. Looking at the latest source I'm wondering if I've somehow got the setup wrong for this - if somehow my profiled connection is containing another profiled connection is containing....
Any help/advice?
Update - looking at http://code.google.com/p/mvc-mini-profiler/wiki/FrequentlyAskedQuestions at least one other person has seen the same sort of problem with 1.7 - although (s)he's doing code first. I'll keep playing to see if I can work out what to do...
Try 1.9. With the update, I just added the new Initialize method in Application_Start and removed the DbProviderFactories config section and now I have SQL profiling with EF (2 databases even, one with code first and one with database first).
protected void Application_Start()
{
....other code
MiniProfilerEF.Initialize();
}