Oracle with Entity Frameworks throws "did not return an object that inherits from DbProviderServices" - entity-framework

I'm working on a solution that uses Entity Framework and Oracle all of which are new territory for me. I'm trying to run some integration tests (these were in place when I got here) and I'm getting the following error:
The 'Instance' member of the Entity Framework provider type 'Devart.Data.Oracle.Entity.OracleEntityProviderServices,
Devart.Data.Oracle.Entity, Version=8.4.407.0, Culture=neutral, PublicKeyToken=09af7300eec23701' did not return an object
that inherits from 'System.Data.Entity.Core.Common.DbProviderServices'. Entity Framework providers must inherit from this
class and the 'Instance' member must return the singleton instance of the provider. This may be because the provider
does not support Entity Framework 6 or later
So I've checked the web.config and it's pointing to a completely different version of that DLL:
<provider invariantName="Devart.Data.Oracle"
type="Devart.Data.Oracle.Entity.OracleEntityProviderServices,
Devart.Data.Oracle.Entity,
Version=8.3.146.6,
Culture=neutral, PublicKeyToken=09af7300eec23701" />
In fact, I can't find a reference to 8.4.407.0 (which I know is installed) anywhere in the solution, but it is in the GAC. Can anyone help me with some pointers on this, banging my head against the wall all morning.
Thanks

Related

Entity Framework inheritance over different assemblies

I'm quite new to Entity Framework, but the more I worked with it, the more I actually liked it. But now my passion is at risk, as I'm struggeling with an issue that already made me crush my head against the wall.
The problem is the following:
I'm using Entity Framework 5.0 with code-first approach plus inheritance for my business models represented by Table Per Hierarchy. At first I had all of my entity types, that were supposed to be mapped, in the same assembly as my DbContext (which worked fine for both TPH and TPT). But as they also contain logic that is dependent on other assemblies, this turned out as no good approach since it caused circular dependencies because those assemblies also need to have knowledge of the Data Access Layer, which in turn has to have knowledge of the entity types that it is supposed to map).
I solved this issue by introducing a CommonObjects project, where I now keep all of my abstract classes and stripped out the concrete descendents (containing the logic, etc.) of those base classes into the specific projects, which are responsible for them.
(see: Circular Dependency Solution)
It compiled and everything seemed to fit the way I imagined it.
But now it turned out that Entity Framework seems to struggle with the derivates being in a different assembly than the base classes.
During runtime, when trying to access the DbContext the first time, the compiler threw an InvalidOperationException saying:
The abstract type 'Foo.Bar.AbstractClass' has no mapped descendents
and so cannot be mapped. Either remove 'Foo.Bar.AbstractClass' from
the model or add one or more types deriving from
'Foo.Bar.AbstractClass' to the model.
So EF is obviously not able to find the descendents, as it only knows the base classes (which are in the CommonObjects project), but the descendents are in a different assembly.
DbSet<AbstractClass> AbstractClasses { get; set; }
According to this question:
Entity Framework Code First and Multiple Assemblies
I tried to add the following code to the constructor of my derived DbContext:
((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(
Assembly.Load("Foo1"));
But that did not work for me. While debugging and watching the MetadataWorkspace the method "LoadFromAssembly" did obviously not have any effect on the MetadataWorkspace and its items (no types were loaded from assembly Foo1).
What am I missing here?
Thanks for your answers in advance.
Ben
EDIT: This only barely works and isn't worth it, and doesn't work at all if you're using CodeFirst.
I have encountered the same issue with code first. I tried your method of reflection. This seems a bit wonky, but you can trick EF into being okay with your set up with an internal class.
internal class ClassToMakeEFHappy : AbstractClass {}
I just created that in the same file as my AbstractClass definition and it did the trick.

problems registering types with structuremap for generic repository

My source is at https://github.com/tonyeung/generic-repo
I want to create a generic repository that I can reference in different projects. Most generic repository implementations that I've seen make that difficult. I stumbled across http://blog.damianbrady.com.au/2012/07/24/a-generic-repository-and-unit-of-work-implementation-for-entity-framework/ and found that it would work great for what I have in mind. Each of my projects can have a context defined in it, then I just need to reference a generic repository project or dll and pass in the context and I'm ready to go.
The only thing I'm trying to get my head around is how do I wire structuremap since there are a few nested dependencies that need to get resolved. Unfortunately, the blog doesn't really address how to implement dependency injection with the generic repository. I tried to tinker around with the implementation (see above referenced git hub repo), but I'm doing something wrong while configuring structure map.
The dependencies work out like this:
the repository takes a context in the constructor, and the context in turn gets a connection string. The constructor parameters are all interfaces which match the default convention of IType maps to Type. My assumption is that since I have auto registration, all I need to do is explicitly define the registration for the context to tell structuremap that it should get the connection string from the app.config, I should be good to go.
However, structuremap is not able to work out the registrations like I thought it would:
StructureMap Exception Code: 202
No Default Instance defined for PluginFamily Generic_Repository_Test.IGenericRepository`1
[[ViewModel.Customer, ViewModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]],
Generic Repository Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
The registration code
//This is commented out since it should not be necessary.
//I tried to put this in for grins
//and see if it would resolve the issue but it doesn't.
//For<IGenericRepository<Customer>>().Use<GenericRepository<CustomerContext, Customer>>();
For<ICustomerContext>()
.Use<CustomerContext>()
.Ctor<string>("connectionString")
.EqualToAppSetting("ConnectionString");
//I've tried moving scan to the top but it didn't make a difference
Scan(x =>
{
x.AssembliesFromApplicationBaseDirectory();
x.WithDefaultConventions();
});
The problem did in fact turn out to be a configuration issue.
The issue was that the app.settings connectionstring setting was returning null, I'm not sure why that happens but I hardcoded the connection string just for grins. Will figure that issue out later.
With that resolved, I still had to manually configure the repo and the context, since another error popped up.
With that resolved, it looks like structuremap was trying to resolve itself, so I had to add a namespace exclusion.
The completed code looks like this:
public class DependencyRegistry : Registry
{
public DependencyRegistry()
{
For<ICustomerContext>()
.Use<CustomerContext>()
.Ctor<string>("connectionString")
//.EqualToAppSetting("ConnectionString");
.Is(#"Data Source=(localdb)\Projects;Initial Catalog=EventStorage;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
For<IGenericRepository<Customer>>().Use<GenericRepository<ICustomerContext, Customer>>();
Scan(x =>
{
x.AssembliesFromApplicationBaseDirectory();
x.ExcludeNamespace("StructureMap");
x.WithDefaultConventions();
});
}
}

EDMX for legacy code _and_ Code First for new development together in one MVC project

The situation as follows:
we have one big MVC project with database first approach on EF5.0:
ObjectContext constructor:
namespace xxx.Models
{
(...)
public partial class xxxEntities : ObjectContext
{
#region Constructors
/// <summary>
/// (...)
/// </summary>
public xxxEntities() : base("name=xxxEntities", "xxxEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
(...)
connection string:
<add name="xxxEntities"
connectionString="metadata=res://*/Models.xxxModel.csdl|
res://*/Models.xxxModel.ssdl|res://*/Models.xxxModel.msl;
provider=System.Data.SqlClient;provider connection string="
data source=.;Initial catalog=xxxdb;
integrated security=True;
multipleactiveresultsets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
We choose Code First for testing the new development on separated namespace.
connection string:
<add name="xxxCFContext"
connectionString="Data Source=.;
Initial Catalog=xxxdb;
Integrated Security=True;
User Instance=False;
MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
DbContext constructor:
namespace xxx.Models.CodeFirst
{
public partial class xxxCFContext : DbContext
{
static xxxCFContext()
{
Database.SetInitializer<xxxCFContext>(new ValidateDatabase<xxxCFContext>());
}
public xxxCFContext()
: base("Name=xxxCFContext")
{
}
(...)
We run add-migrations, update-database without problem, the build completed with success.
But on the first time with the code-first db access:
xxxCFContext cfdb = new xxxCFContext();
foreach (Xobject xobject in cfdb.Xobjects)
Appear the error:
"Could not find the conceptual model type 'xxx.models.yyyclass'", but this yyyclass exist in edmx, NOT the codefirst part.
Uninstall EF5.0, install EF6.0 and the error disappeared. But i need the EF5.0 not the 6.0 alfa3 prerelease.
What's wrong? How can we use edmx mixed with codefirst with EF5.0?
I would be very grateful for any idea.
EDIT
I know this workarounds, but not help for me:
Have anyone used Entity Framework with code first approach mixed with Edmx file?
http://blog.oneunicorn.com/2012/02/26/dont-use-code-first-by-mistake/
Could not find the conceptual model type
http://blog.oneunicorn.com/2012/02/26/dont-use-code-first-by-mistake/
Entity Framework (4.3) looking for singular name instead of plural (when entity name ends with "s")
Building an MVC 3 App with Database First and Entity Framework 4.1
The problem of generating (with xxxmodel.Context.tt and xxxModel.tt) the large existing edmx heavily exploits the advantages of ObjectContext, so we can not simply change from the ObjectContext to the DbContext (behind the existing edmx).
Edit II
From DB First to CodeFirst, we choose the following:
Moved from old edmx file to Code generation. With EF 5.x DbContext Fluent Generator was generated the model objects, so we have the model objects.
(Right-click into EDMX editor and add code generation item. If you do not seem, to be installed: Tools menu, Extensions and Updates, EF 5.x DbContext Fluent Generator)
The model objects and the context is copied from the EDMX.
The EDMX was deleted anything that was under him.
Set the ConnectionString from was difficult EDMX-style to simple codefirst form.
and tadam, in about 10 minutes, we moved from Database First to Code First. During development, with existing 80 tables in db.
run Enable-Migrations in Power Management Console, and continued with CodeFirst.
It may help to keep the different "types" of EF (code-first, database first, etc.) in separate assemblies: a limitation of EF is that it is not possible use code-first in an assembly with certain database-first attributes - though a newer version of EF may fix this (perhaps that's why EF6 alphas work for you).

Entity Framework Code First and Multiple Assemblies

I have a subclass in a different assembly to its base class. The parent is a POCO class used for EF Code First.
When I try to add an instance of inherited class to the database I get InvalidOperationException: "Object mapping could not be found for Type with identity 'Foo.Bar.MyInheritedClass'".
It works fine if subclass is in same assembly as base class.
In regular EF the solution seems to be a call to ObjectContext.MetadataWorkspace.LoadFromAssembly(assembly). But I can't figure out how this relates to Code First.
Any advice?
I'm using Entity Framework 4.1 RC.
I solved this by inheriting from the first assembliy's DbContext, adding a DbSet<> for the derived class, and then adding new instances of derived type to to that.
Posted code on MSDN forum here.
I know this post is a bit old, but I was able to accomplish this using #Dave's recomendation inside the constructor:
public Context() {
((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(
System.Reflection.Assembly.GetAssembly(
typeof(--[Inherited DbContext]--)));
}
I'm quite new to EF (Entity Framework 4) and I got the same exception when I made changes in the model.
My problem turned out to be that I did not know EF need all the names on all the navigation properties to agree, not only their type. For example if there is a navigation property named foo, then there needs to be a declared variable in the corresponding class with the very same name.

Why is my WCF RIA context throwing FileNotFound exceptions during unit tests?

I'm trying to write unit tests involving my WCF RIA entity proxies and when I try to access an entity's parent or child properties through an association I get a FileNotFoundException when the WebContext class fails to load System.Xml.
For example, I have two entities defined in my web project in Entity Framework - Course and CourseUnit. A Course has many CourseUnit children. I'm not exposing any RIA contexts or anything to my ViewModels, they are all hidden behind interfaces. I'm using Moq to mock these interfaces and return the standard RIA entity proxies to my unit tests.
This works fine when I'm testing things like
Assert.AreEqual("title", course.Title)
where course is an instance of the RIA proxy. However, if I do something like
Assert.AreEqual(0, course.CourseUnits.Count)
I get the following exception
FileNotFoundException was unhandled by
user code Could not load file or
assembly 'System.Xml, Version=2.0.5.0,
Culture=neutral,
PublicKeyToken=7cec85d7bea7798e' or
one of its dependencies. The system
cannot find the file specified.
And similarly if I execute any code in a unit test that involved one of these relationships then the code throws the same exception. Basically if I ever try to access these properties with association relationships from my tests they break.
The exception actually occurs in generated code. It an be found in the file [webProjectName].g.cs in the partial class Course : Entity and happens in the CourseUnits getter.
Any ideas?
Edit - I added a reference to the EntityFramework assembly and the exception has changed to the same thing but System.ComponentModel.DataAnnotations instead of System.Xml. Needless to say I have tried referencing both assemblies in the unit test project, and it didn't work.