Entity Framwork Unable to Load the specified metadata resource - c#

So I have set up a SQL Server and EF in my project.
MPSDBEntities mpsEntities = new MPSDBEntities();
And it works fine when I do a save changes. e.g
mpsEntities.SaveChanges();
it updates the database (does it mean my connection string is correct?)
However, whenever I tried to perform any kind of load data/SQL from the EF, such as
var temp = mpsEntities.CARD_BY_CHECKTYPE.Where(x => (x.CHECK_TYPE == "AA2")).ToList();
It would throw an exception of
Unable to Load the specified metadata resource.
Here is my connection string, which I doubt is where the problem is at:
<add name="MPSDBEntities"
connectionString="metadata=res://*/MPSDBModel.csdl|res://*/MPSDBModel.ssdl|res://*/MPSDBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=PAE0DT-DDWB282\MPS2;initial catalog=MPS;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework""
providerName="System.Data.EntityClient" />
I went through the following posts. They didn't solve my problem.
System.Data.MetadataException: Unable to load the specified metadata resource
MetadataException: Unable to load the specified metadata resource
Entity Framework: Unable to load the specified metadata resource
Unable to load the specified metadata resource
Anyone know what the problem is?
Thank you.
#petryuno1
Here is my DbContext, if this is what you are asking..
public partial class MPSDBEntities : DbContext
{
public MPSDBEntities() : base("name=MPSDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<CARD_BY_CHECKTYPE> CARD_BY_CHECKTYPE { get; set; }
........
}

This worked for me.
Changing from this:
connectionString="metadata=res://*/Model.Project.csdl|res://*/Model.Project.ssdl|res://*/Model.Project.msl;
change to:
connectionString="metadata=res://*/;
And add the rest of your connection string after. Hope it helps.

Related

Avoid Oracle schema name with Entity Framework

I'm using the Official Oracle SQL and Entity Framework driver to read the database. But when reading the database it prefixes the table name with "dbo".:
SELECT
*
FROM "dbo"."Woningen"
Without the "dbo". prefix the code works fine, with, it causes the error "table or view does not exist". This is probably because the user isn't 'dbo', so it does not have access to that schema. This is the Entity Framework code that I'm using:
[Table("Woningen")]
public class Woningen
I've tried updating the Oracle nuget package but then it comes up with the error "Connection string is not well-formed". So it probably has the same error as before, it just failed sooner. This is the connectionString format I used:
<add name="DefaultConnection"
providerName="Oracle.ManagedDataAccess.Client"
connectionString="USER ID=testUser;PASSWORD=password;
Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=serverUrl)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=Database)));"/>
I can see three possible solutions to this problem, but have no idea how to implement them:
Manipulate Entity Framework to exclude schema names from queries
Give my user access to the schema
Update the driver and fix the connectionstring format, if anyone knows how the format changed..
Note that current code already works in production so the current version should be fine. The database and it's user are new, so the problem could be with how they are created.
You can specify the schema that Entity Framework uses. See below
If you are using Entity Framework 6+ you can use the following
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Set a default schema for ALL tables
modelBuilder.HasDefaultSchema("YourSchemaName");
}
}
If you wish to set a schema on a specific table...
[Table("Woningen"), Schema = "YourSchemaName")]
public class Woningen { }
If you are using EF5
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Unfortunately you have to specify each table you want to set a schema for...
modelBuilder.Entity<Woningen>().ToTable("Woningen", "YourSchemaName");
}
}

Entity framework error when enable migrations

I already had a database first ASP MVC project. Now I remove .edmx file and and all every thing related to database first and make it code first. When I want to Enable-Migrations I get this error in powershell. :
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
Here is my Connection string in webconfig:
<connectionStrings>
<add name="Context" connectionString="Data Source=.\;AttachDbFilename=|DataDirectory|\myDbName.mdf;Initial Catalog=myDbName;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
And Here is my Context :
public class Context : DbContext
{
public Context()
: base("name=Context")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
How can I resolve this problem?

The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development

I m trying to migrate a project initially developed using EF4 to EF6, to take advantage of EF6 transactions management.
The problem I m facing is that the project has been created using the Database First approach, so when I m using code like context.Database.UseTransaction, I m encountering the following error:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.
This exception triggers inside the OnModelCreating method of my DbContext class.
Any idea ?
Thanks
EDIT:
The thing is that it's legacy code using EDMX with database first approach. I have to implement EF6 transactions inside this project, so it should now be more like a code first pattern.
In addition, here's the context class:
public class MyContext : BaseDbContext
{
public MyContext (DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
}
And the connection string:
<add name="CS"
connectionString="Data Source=MyServ;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework;Enlist=false"
providerName="System.Data.EntityClient" />
I tried setting the providerName to System.Data.SqlClient but it doesn't change anything.
Please note that the original connection string was in the database first format:
<add name="OrderManagement"
connectionString="metadata=res://*/MyManagementModel.csdl|res://*/MyManagementModel.ssdl|res://*/MyManagementModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MyServer;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework""
providerName="System.Data.EntityClient" />
If I try to open a connection whilst I keep the connection string in the database first format, I m facing the exception Keyword metadata not supported, and when I put the connection string on the code first format, I m facing the error The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.
The most common mistake when converting context from database-first to code first is forgetting to remove the generated OnModelCreating. In a database-first context, OnModelCreating throws the exception:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException(); // ← throws exception
}
So take a look at your context or its base class (and their partial classes) and if it's like above code, you should remove it.
Also your code and configurations need some changes.
You are using providerName="System.Data.EntityClient" for a code first context. You should change the connection string to something like this:
<add name="MyContext" connectionString="data source=server;
initial catalog=database;User Id=user;Password=password;
multipleactiveresultsets=True;application name=EntityFramework"
providerName="System.Data.SqlClient" />
Then you should change your context constructor to something like this:
public partial class MyContext: DbContext
{
public MyContext() : base("name=MyContext") { /* . . .*/ }
// . . .
}
Also if you want to have a common base class, follow above instructions.
Note: To create code-first from an existing database, you can right click on project and choose Add New Item, then under Visual C# under Data select ADO.NET Entity Data Model and click on Add. Then from the Entity Data Model Wizard choose Code First from Database and follow the wizard. For more information see Entity Framework Code First to an Existing Database
You Have to Just Copy Connection String from App.config and Paste it into your Web.config file.
Make Sure your EDMX has updated to latest connection with database.
This works for me.
I just connection string in web.config like this
connectionString="metadata=res:///Models.wimEntities.csdl|res:///Models.wimEntities.ssdl|res://*/Models.wimEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=DATABASE;persist security info=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"

Entity Framework Error unable to load the specified metadata resource [duplicate]

This question already has answers here:
MetadataException: Unable to load the specified metadata resource
(47 answers)
Closed 6 years ago.
Yes I did read and try entity framework Unable to load the specified metadata resource
I typically use code first and have had no issues. However I needed to troubleshoot a project with EDMX
Context:
public partial class x500Entities : DbContext
{
public x500Entities()
: base("name=x500Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<WorkerPublicExtended> WorkerPublicExtendeds { get; set; }
}
connection string :
<add name="x500Entities"
connectionString="metadata=res://*/CDISWorkerPublicExtended.csdl|res://*/CDISWorkerPublicExtended.ssdl|res://*/CDISWorkerPublicExtended.msl;provider=System.Data.SqlClient;provider connection string="data source=xserver;initial catalog=x500;persist security info=True;user id=xuser;password=xpassword;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient"/>
ERROR :
An exception of type 'System.Data.Entity.Core.MetadataException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Unable to load the specified metadata resource.
Upon hitting this line:
return context.WorkerPublicExtendeds.FirstOrDefault(x => x.upperIDSID == idsid.ToUpper().Trim());
Complete Method :
public WorkerPublicExtended GetEmployee(string idsid)
{
using (x500Entities context = new x500Entities())
{
return context.WorkerPublicExtendeds.FirstOrDefault(x => x.upperIDSID == idsid.ToUpper().Trim());
}
}
Why is this happening?
I connected to sql server ssms and I don't see the table WorkerPublicExtended that I have seen in diagram edmx and the model, I don't see where that name is translated to a real table name. How is this?
Probable causes:
1) your resource file is nowhere to be found in you project (this resource file is configured in you app.config in connection string) confirm oyu have it.
2) when you say you connect to the database and you don't see the Table then you're in the wrong database? that should never happen, you have an EDMX generated for another database, or someone droped the table and didn't regenerate the edmx ? :X
If you have 200% sure that the database you are connecting it's the latest in schema, procedures, views, etc, or it's the production database, why not to delete the entire edmx and recreate, test and redeploy?
The three parts of the EMDX look correct in the connection string. After double-checking this part to be correct (refer to this guideline to troubleshoot your issue):
You might have changed the MetadataArtifactProcessing property of the model to Copy to Output Directory, or
You changed other things (like the name of an assembly), or
You might be using a post-compile task to embed EMDX which is no longer working.
Source from here.
Also check the entire string for correct syntax.

The default DbConfiguration instance was used before the 'EntityFrameworkConfiguration' type was discovered

public class EntityFrameworkConfiguration : DbConfiguration
{
public EntityFrameworkConfiguration()
{
this.SetModelCacheKey(ctx => new EntityModelCacheKey((ctx.GetType().FullName + ctx.Database.Connection.ConnectionString).GetHashCode()));
}
}
To make the above code work i have added below line in web.config
But for other project where i am using the assembly reference i am getting exception:
{"The default DbConfiguration instance was used by the Entity
Framework before the 'EntityFrameworkConfiguration' type was
discovered. An instance of 'EntityFrameworkConfiguration' must be set
at application start before using any Entity Framework features or
must be registered in the application's config file. See
http://go.microsoft.com/fwlink/?LinkId=260883 for more information."}
Your question doesn't state how you are using this custom DbConfiguration.
You could get this error a couple of different ways.
Configuration style setup
as described here: Entity Framework Config File Settings
Configuration as code
as described here: Entity Framework Code-Based Configuration (EF6 onwards)
You can hack at this style by doing things like DbConfiguration.SetConfiguration(xxxx). I didnt find this useful at all.
What this really comes down to is how you construct your DbContext.
Configuration file style constructors
https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/DbContext.cs#L75
With no arguments - EF6 is uses the configuraiton files to determine the right DbCofniguration to use
with some "connection string-like" arguments again EF6 is using configuration files to determine the DbConfiguration
no config, or bad config - and you will get this sort or exception
Configuration as Code style constructors
https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/DbContext.cs#L139
I think this yields better control.
Attribute your DbContext, then use a manually created DbConnection
public class EntityFrameworkConfiguration : DbConfiguration
{
public EntityFrameworkConfiguration()
{
this.SetModelCacheKey(ctx => new EntityModelCacheKey((ctx.GetType().FullName + ctx.Database.Connection.ConnectionString).GetHashCode()));
}
}
[DbConfigurationType(typeof(EntityFrameworkConfiguration))]
public class MyContext : DbContext
{
public MyContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{ }
public DbSet<Stuff> Stuff { get; set; }
}
using(var conn = new SqlConnection(asqlserverConnectionString))
using (var db = new MyContext(conn, true))
{
var value = await db.Stuff.Where(s => s.xxx.Equals(primaryKey)).Select(s => new { s.BinaryContent } ).SingleOrDefaultAsync();
}
If you are using Code-based configuration, try updating the config file thusly:
<entityFramework codeConfigurationType="MyNamespace.MyDbConfiguration, MyAssembly">
...Your EF config...
</entityFramework>
In my case i have two different edmx files and both are in different class libraries.
I got this error when i added those two libraries in the same project.
I don't have any single clue how is that sorted out but; when i call any method from my first DbContext class, the second one worked like miracle happened. It was throwing this error when second context class called first.
My Ef version is: 6.4

Categories

Resources