I know this question was already asked but it seams that my case might be slightly different. I tried the "run custom tool" but here's where the strange thing happens: Because i'm having 2 related databases (so 2 related models). If i'm running the custom tool on one model it screws up the other and vice-versa(incomplete .cs files, missing, etc.). Does anyone have any ideea where i'm going wrong?
EDIT:
the complete error:
An exception of type 'System.Data.Entity.Core.MetadataException'
occurred in EntityFramework.dll but was not handled in user code
Additional information: Schema specified is not valid. Errors:
The relationship
'ProductionMasterDataEntityModel.FK_ProductGroup_CostPeriods' was not
loaded because the type 'ProductionMasterDataEntityModel.ProductGroup'
is not available.
The following information may be useful in resolving the previous
error:
The required property 'CstAveOrderQty' does not exist on the type
'SISCOM.Persistance.Models.ProductGroup'.
The custom tool is: TextTemplatingFileGenerator
I'm not sure if it has anything to do with the asp.net framework but it is an asp.net project so i thought it's worth mentioning.
in my case, this Issue came after I update .edmx file. Remove all the tables on it and re-update it.right click on .tt file(Eg. Entity.tt) file->Run custom tools. then my issue solved.
I solve this case like below.
Entity in class lib project and i was try to consume in other project.
So in that project i have add reference "EntityFramework.SqlServer.dll" in new project.
Drop the model from edmx and add it again should sort it out. Note this cannot be reverted unless using source control tools.
It seams that i had 2 problems contributing to that error.. First, there were some stored procedures and views, after i got that out of the way (deleted my models, created them again and i've unchecked the option to include the stored procedures and i only added the tables to the model, no views and no stored procedures) i could access some data but not all of it.. The second problem was that i forgot to add a connection to the dependent database.
So the methods in my repository look like this:
public myType GetSomething()
{
var db = new model();
var dependencyDb = new dependencyModel();
//do whatever needs to be done with the data before presenting it
return something;
}
P.S... i didn't had to explicitly take it to the needed table, after i added the connection it found all that it needed by itself.
Hope this helps anyone having this problem.
Related
I see that this question has been asked quite a bit, but none of the solutions have helped me since I'm using model first and not code first.
I have a C# project in VS 2015 using EF6. I am building a database using the model first approach and can successfully generate the SQL code from the model and run it in SSMS. I'm using SQL Server LocalDB.
The problem I have is that whenever I try to add a programmatically created entity to the collection (table) to which it belongs, I always get the error
An exception of type 'System.Data.Entity.Core.MetadataException' occurred in mscorlib.dll but was not handled in user code
Additional information: Schema specified is not valid.
Errors:
Market.ssdl(184,6) : error 0040: The Type nvarchar(max) is not qualified with a namespace or alias. Only primitive types can be used without qualification.
The entity I'm creating is has only one property; a string (or nvarchar(max) in the database). Again, I can create the object, but the moment I try to add it to its collection (or table) before saving any changes, I get the above error. I even tried not naming the Name property, but the error persists.
using (var context = new MarketContainer())
{
// Create data source
var datasource = new DataSource()
{
Name = dataSourceName
};
// Save data source
context.DataSources.Add(datasource);
}
Another SO answer proposed to right click on the .tt file and clicking "Run Custom Tool", but that didn't do anything.
I tried this once with MySQL and it worked fine! Now that I need to move to SQL Server it doesn't work... I've been stuck on this problem for over a week, so really any help would go a long way.
The issue has been resolved. I was referencing the project which contained the entity model from another project, and the App.configs were not matching. Once I copied the contents from the entity project's config file to the referencing project's, everything began working properly.
Hopefully this helps someone other than myself!
Maybe an odd question, but we have a scenario in which we want to use Entity Framework code-first in an environment which could have a database with a newer/higher version than the code itself.
Let me elaborate a bit. We have a couple of solutions which all use a core assembly which contains the overall datamodel which all solutions are using. The solutions are mainly sites and apps which are deployed to several different Azure Web Sites. So the solution are running next to each other. The only thing they are sharing is the Azure database.
Now the scenario will come in play. When we update the database model in the core assembly and update one of the solutions in Azure. The underlying database will be updated when the model is loaded within that solution. No problem there, works like a charm...
The problem starts when one of the other solutions is loaded. These other solution are still using the previous core assembly which has now an outdated EF CF model compared to the database model they are connecting with. So a nice exception will be throw as shown below.
The model backing the '{NAME}' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.
The question is whether we can force the model just to load and ignore the changes made within the database. We internally have a policy to only apply not breaking changes within the database, so the model should be able to load without any problems.
Thanks in advance for the information and tips!
I can be wrong(not sure whether I remember correctly), but if it doesn't interferes with your application configuration, you can set DB initializer to null:
public PortalDbContext()
: base("name=PortalConnectionString")
{
Database.SetInitializer<PortalDbContext>(null);
}
Or it could be possible to create custom initializer:
public class BlogContextCustomInitializer : IDatabaseInitializer<BlogContext>
{
public void InitializeDatabase(BlogContext context)
{
if (context.Database.Exists())
{
if (!context.Database.CompatibleWithModel(true))
{
// Do something...
}
}
}
}
If you're using EF Code-First, the model must match the database.
Even if you found a way to circumvent that limitation you'd be doing something dangerous.
Let me expalin it: if you update the database from "Solution A", the model in "A" will match the database, and any further changes to the model in this solution can be applied to the database without any problem at all. That's right!. However, if you do what you're asking in this question, i.e. you do something so that "Solution B" can keep working even if the model doesn't mathc with the DB, and then you make a change to the model in "Solution B", how do you apply it? how can "Solution B" know what changes to apply? how can "B" determine what changes made by "A" should be left as they are, and what are the new changes made by "B" that must be applied to the database?
If you could follow on like this, you'd finish with two different code first models, none of which matches the database, and, besides, how could you warranty that both applications work correctly? how can you ensure that changes on "A" doesn't affect code on "B" and viceversa?
The safest solution to avoid this problem is to share the assembly containing the code first model between both solutions. Any other solution will be troublesome sooner or later. Perhaps you'll have to refactor your solutions so that they can share the same DbContext. The DbContext must be the only thing in your project. I usually have an Entities project, and a DbContext project which has a reference to Entities. Then both solutions would have references to these projects. These projects can be in one of the solutions, or in a completely different solution. Of course in one, or both solutions, you'll have to add a reference to the DbContext assembly, instead of the project, and keep it updated, for which you can use post-build scripts. In this way, when you recompile your solutions you'll also detect incompatible changes made for one solution which adversely affects the other.
EF6 supports several different DbContexts in the same database, so, if each of your applications had a different, non conflicting DbContext, you wouldn't have a problem. I cannot check it right know, but I think that the name of the DbContext must be different in each solution (I don't remember if the namespaces are taken into account). By non conflicting I mean that they refer to different database objects (tables, views, or whichever), of that the objects refered to by both contexts are not changed (for example master tables).
Hopefully what I'm after is possible at all. I'm currently looking at a way to do what Entity Framework Code First migrations does when you use Package Manager Console in Visual Studio but do it in runtime. The two processes I'm after are Add-Migration and Update-Database.
To explain a bit more, I want to be able to construct custom meta data for the Model and compare that against existing or non-existing database. This should output the same migration file that you get from Add-Migration command in Package Manager console.
After I've got one or more migration files I want to run the Update-Database command again in run-time, programatically to apply Up / Down changes to the database.
The key point is to be able to provide a completely custom (virtual?) model meta data to the Add-Migration procedure, not one based on actual poco classes.
If anyone has done something similar before, I'd appreciate any pointers on where to look as I didn't have much luck with Googling / EF documentation.
EDIT:
To address the WHY: I want my users to be able to define their structures in run-time. They would define the structure as part of a changeset and then be able to apply one or more changesets to the underlying database. Essentially, users would do from web-ui what a developer does from visual studio, except that the classes won't be .cs files but instead a class description in a relational database.
EF seems like a perfect fit to do this because it already does everything I need it to do. I've done schema comparison and run-time change mechanisms in the past. Since EF already does this, I don't want to reinvent the wheel. The migration files that EF Code First outputs are also a perfect fit fro what I'm trying to do.
The reason I haven't yet dug into the EF source is I wanted to check if someone else has attempted this before and if they can share and pointers. Some concrete questions:
What class / method do I need to be able to run schema compare?
How do I hook into that process to supply my own meta-data for "POCO" classes?
What are the options for outputting the detected schema changes (the Up, Down and Seed methods)? Ideally I'd like to compile a change set into a satellite assembly when user chooses to apply changes.
How can one run DbMigration instances in run-time?
I'm after some concrete examples.
So.
I'm having trouble fixing this little problem.
I have several classes, and it's all nice and good. Right up until now. I have now added another class (MatchResult), and it works.
But when I try to make the correct association:
It fails with a runtime exception.
Error:
Schema specified is not valid. Errors:
The relationship 'DbModel.FK_ProductPrice' was not loaded
because the type 'DbModel.Product' is not available.
The following information may be useful in resolving the previous
error:
The required property 'MatchResults' does not exist on the type
'PriceMonitor.Model.Product'.
The relationship 'DbModel.FK_WebshopProduct' was not loaded
because the type 'DbModel.Product' is not available.
The following information may be useful in resolving the previous
error:
The required property 'MatchResults' does not exist on the type
'PriceMonitor.Model.Product'.
It seems - for some reason - that EF does not create the MatchResults property on the Product class.
This approach has worked on every single class I've ever made using EF. Up until now.
I found the answer. Apparently, it is a confirmed bug in the Entity Framework. (WHAT?!)
It seems, if you place the .emdx file in a subfolder, automatic code generation does not work.
See this question.
I just had the same error, the name of my csdl, ssdl and msl were not the same als the name of my edmx and contained the name of a other edmx I had within my solution. I changed the connectionstring and fixed it.
This happens when using EF Database First and the generated POCO classes are not up to date with the edmx file, for example when POCO classes are in a different project than edmx.
I have urgent and unexplainable problem so any help would be appreciated. I haave 2 different databases which are exactly the same except there is different data in each of them.
I have a web application using LINQ-To-EF and until I've changed the database in connection string everything was working fine. Even though the databases are exactly the same I receive the error: "Invalid column name 'tema_id'." The problem is that "tema_id" doesn't exist in any of those two databases, however, somehow it does exist in .edmx file. The name of the mapping should be "aktivnost_id" and not "tema_id" how it is now.
I've tried updating the model from the database, but in that case everything gets wrong and I get dozens of different errors in Error List.
I've provided the screenshot of mapping details for the problematic table (you can see "tema_id" which should be "aktivnost_id").
I know my explanation might be a bit confusing, but if any additional info is needed I will provide it.
It I hard to give a complete answer without the full details of the errors that occur when you try to update; however, I would be sorely tempted to edit the EDMX as XML, use "find" to locate tema_id, and fix directly.
If nothing else, it is quick to try :)
Have you tried to edit the .EDMX file directly to match the actual table structure?
Try to generate whole data access layer manually outside of visual studio through edmgen.exe
use the following command for EF4 (adjust parameters to reflect your db name, username, password)
#"%windir%\Microsoft.NET\Framework\v4.0.30319\edmgen.exe" /mode:fullgeneration /c:"Data Source=tcp:127.0.0.1;Initial Catalog=your_database;User ID=sa;Password=your_password;Integrated Security=False;" /project:DataContext /entitycontainer:DataContext /namespace:Project /language:CSharp /pluralize