I am new to MVC web application development.
I am trying to add a controller after adding my model and DbContext class.
But when i am trying to this controller using Entity framework it gives me an error of
Unable to cast object of type 'System.Data.Entity.Core.Objects.ObjectContext' to 'System.Data.Objects.ObjectContext'
I am using EF-6.1.1 (latest update)
Following are my Model and Context Class..
public class EmpDetails
{
[Key]
public int Id { get; set; }
public string EmpId { get; set; }
public string EmployeeName { get; set; }
}
public class ModelContext : DbContext
{
public DbSet<EmpDetails> Employee { get; set; }
}
When i am trying to add a controller I get following error.
Please suggest some solution to this problem. what is going wrong with it..
here is the process through which i am adding Controller
Entity Framework brought breaking changes between versions 5 and 6. In order for it to go completely open source, they moved all of the libraries out of band and they are now all completely within the EntityFramework assembly in NuGet. A side effect of this was that many of the namespaces for Entity Framework has changed:
The namespaces for DbContext and Code First types have not changed.
This means for many applications that use EF 4.1 or later you will not
need to change anything.
Types like ObjectContext that were previously in
System.Data.Entity.dll have been moved to new namespaces. This means
you may need to update your using or Import directives to build
against EF6.
The general rule for namespace changes is that any type in
System.Data.* is moved to System.Data.Entity.Core.*. In other words,
just insert Entity.Core. after System.Data. For example:
System.Data.EntityException => System.Data.Entity.Core.EntityException
System.Data.Objects.ObjectContext =>
System.Data.Entity.Core.Objects.ObjectContext
System.Data.Objects.DataClasses.RelationshipManager =>
System.Data.Entity.Core.Objects.DataClasses.RelationshipManager
The reason you are seeing the error is that you are using a previous version of MVC, which was targeting an earlier version of Entity Framework. The scaffolding is going to be assuming the old namespaces.
You can try upgrading to the newest version of MVC and your scaffolding will work again. Either that or downgrade EF6 (I don't recommend this, it has a lot of really great features). The third option is to manually fix your scaffolded code every time.
While using ASP.Net MVC 3/4, Entity framework assembly (.dll) would be automatically referenced with a lower version (5.0.0.0). And when you update this to a higher version an explicit type conversion is required for which you are getting this error. one way to fix this problem is, use the existing version of Entity Framework (5.0.0.0) without updating to higher version.
Related
I need to map to a view when using EF6 with migrations.
The view pivots 2 other tables to enable a simple summary view of the underlying data, the idea being it allows us to use this in a summary index view.
The issue I have is I am unable create a migration that either deploys the view (ideal goal) or deploys the DB without the view for later manual deployment.
In most attempts, following other SO questions, I end up either deadlocking the Add-Migration and Update-Database commands or generally causing an error that breaks one or the other.
What is the current best way to use EF6 to access views, even if I lose the ability to automatically deploy them with the migrations, and not cause errors with migrations.
Further detail
The Db contains 2 tables Reports and ReportAnswers. The view ReportView combines these two and pivots ReportAnswers to allow some of the rows to become columns in this summary view.
Reports and ReportAnswers were depolied via EF Migrations. The view is currently a script that needs be added to the deployment somehow.
Reports, ReportAnswers & ReportView are accessible from the db Context
public virtual DbSet<ReportAnswer> ReportAnswers { get; set; }
public virtual DbSet<Report> Reports { get; set; }
public virtual DbSet<ReportView> ReportView { get; set; }
I have tried using Add-Migration Name -IgnoreChanges to create a blank migration and then manually adding the view to the Up() and Down() methods but this just deadlocks the migration and update commands, each wanting the other to run first.
I have also tried using modelBuilder.Ignore<ReportView>(); to ignore the type when running the migrations but this proved incredibly error prone, even though it did seem to work at least once.
I just walked around interesting article about using views with EF Core few days ago, but I found also the very same using EF 6.
You may want to use Seed method instead of migration Up and Down methods.
protected override void Seed({DbContextType} context)
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
var baseDir = Path.GetDirectoryName(path) + "\\Migrations\\{CreateViewSQLScriptFilename}.sql";
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir));
}
Your SQL command should look like sample below.
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[{ViewName}]'))
EXEC dbo.sp_executesql #statement = N'CREATE VIEW [dbo].[{ViewName}]
AS
SELECT {SelectCommand}
It is not perfect, but I hope at least helpful.
I found another blog post about this topic and the writer says to use Sql(#"CREATE VIEW dbo.{ViewName} AS...") in Up method and Sql(#"DROP VIEW dbo.{ViewName};") in Down method. I added it as you didn't supplied the code from Up and Down migration methods. Maybe good idea will be to add SqlFile instead of Sql method.
There is also option to create customized code or sql generator and plug it in to migrations, but I guess it is not the things you are looking for.
Let me know in comment in case you need additional help.
Related links:
Using Views with Entity Framework Code First
EF CODE FIRST - VIEWS AND STORED PROCEDURES
Leveraging Views in Entity Framework
DbMigration.Sql Method (String, Boolean, Object)
DbMigration.SqlFile Method (String, Boolean, Object)
I have some issues with Entity framework 6.2. I change ef version and now I have a lot bug..
EF version: 6.2
Visual studio version: 15.5.2
.Net version: 4.7.1
OS: Windows 10 Pro 1709
1.NotMapped why not working any more with inheritance? My example class:
public class BaseClass {
public string MappedProp {get;set;}
public virtual string NotBeMappedProp {get;set;}
}
public class Test : BaseClass {
public string MappedProp {get;set;}
[NotMapped]
public override string NotBeMappedProp {get;set;}
}
add-migration not found entity framework on project. But I installed it already. Besides, I deleted all packages folder. However still continue same exception.
I open clean project but suprise... I have a new proplem. My foreign keys thrown an exception.
Unable to determine the principal end of an association between the
types x1 and x2. The principal end of this association must be
explicitly configured using either the relationship fluent API or data
annotations.
My code part looking like that:
public class Student{
.....
public string Name {get;set;}
public long? LocationId {get;set;}
[ForeingKey("LocationId")]
public Location Address {get;set;}
......
}
public class Location{
public long Id {get;set;}
........
}
It is working with previous version.
I have no migration, I updated my database, check table but entity framework still said, there is an migration.
the model backing the context has changed since the database was
created
Try add abstract modifier to BaseClass definition. NotMapped attribute should be at the lowest level. If you need to map overridden property you should map it with Column attribute directly in inherited class.
Try run command Install-Package EntityFramework -Version 6.2.0 -Project {{EFProjectName}} to reinstall package and reference it correctly.
You better want to specify ForeignKey attribute in Address class and its StudentId property(or whatever you call it). It is one-to-zero-or-one relationship.
Information about migrations are stored in the database table __MigrationHistory along with compiled db model to speed things up(checking everytime if code suits database is time consuming) and that is the reason you get that error. You have different compiled model in your code and different stored in the migration history. You can create empty migration running command Add-Migration -Name ManualDbUpdate -IgnoreChanges to overcomes this, but you must be sure code model and database model are equal. If not you are going to get exceptions.
I have an MVC 5 application that uses Entity Framework 6 Database First approach.
So far It is working well, but I have come across an unwanted behaviour.
If I select 'Update Model From Database', select the 'Add' Tab, and then select the Tables or Views I would like to add and click Finish, it adds the Tables and/or Views I specified no problem.
However, the unwanted behaviour is that, even though I didn't select the Refresh Tab, it seems every single model is automatically being refreshed.
This means all my custom Attributes on my models are being removed.
Is there any way to specify to only add the specified Tables or Views without refreshing all models, or if it refreshes all models, to retain the Attributes I have specified?
Visual Studio information: Microsoft Visual Studio Professional 2013
Version 12.0.40629.00 Update 5
Microsoft .NET Framework
Version 4.5.51650
Installed Version: Professional
Is this a bug or intended use?
Thanks
Neill
In order to modify autogenerated classes it's advised to use a partial class, that way your changes won't be lost when the class is refresh / generated again.
Simple example of a class and a partial class expanding on its attributes and methods
// Assume this is autogenerated by EntityFramework
public class Book {
public int Id {get; set;}
public string Title {get; set;}
}
// In a different file.cs
public partial class Book {
[Required]
public string Author {get; set;}
public override ToString(){
// Some code goes here
}
}
In that example, if EntityFramework generates a new Book model, the changes you've done to that model via the partial class won't be lost at all.
Check out this article for more information on partial classes and this question for more info on the advantages of using partial classes.
Edit: if you need to add attributes to existing properties of your autogenerated class this answer might help you out as well.
You really need to use partial classes so that you can refresh the edmx to your heart's content.
look here for a great tutorial on the subject.
I have an issue with Code First. I just migrate the project from Model First to Code First and I think that Entity Framework is losing its mind... Here is my class (simplified) :
public class MyClass
{
// Key, other properties...
public bool? MyNullBoolean { get; set; }
public static void Configure(EntityTypeConfiguration<MyClass> myClass)
{
// Other configuration on other properties...
myClass.Property(m => m.MyNullBoolean).IsOptional();
}
}
Here are some additionnal informations for you :
I call the Configure() method in the OnModelCreating() method.
Migrations are enabled and Automatic mode is set to false
In my migration I have MyNullBoolean = c.Boolean(nullable: false), so EF
is acting like this property is required, wich is not as previously
seen.
I target an existing DB (dev) with data inside so I can't perform Migration "for testing purposes"
This is the exact same model as the one from Model First and that last one is working correctly...
Here is what I tried :
Disabling / Enabling EF on the project (deleting Migrations in project and db)
Restarting VS
Targeting another DB (same structure)
Leave the property unconfigured (so EF do the job alone)
I'm out of idea and I found nothing in the Internet. Thanks for your help guys !
I think that EF was corrupted because when I uninstall it, clean the solution, install it, rebuild the solution, it worked.
So there was no problem with db or my model.
I'm upgrading from Entity Framework 4.1.0.0 to Entity Framework 6 and I'm having a really hard time tracking where all of the old classes went and what namespace things are in these days.
I've got a class that looks like this and was using these attributes but now I
[Key, Column(Order = 1)]
public int PersonID { get; set; }
[Key, Column(Order = 2)]
public int WorkoutID { get; set; }
etc...
Can't figure out what namespace the attributes are in
Even figure out if I'm supposed to be using them
Can't nuke the EF class lib and rebuild it because the DB is code-first - I think..
Disclaimer: I've never really worked from code-first because I like being able to rebuild my edmx file from scratch
Can anyone point me in the right direction? MSDN docs have some up short, the EF 6 upgrade guide (found here: http://visualstudiomagazine.com/articles/2014/03/01/whats-new-in-entity-framework-6.aspx) doesn't contain what I need and you'll all my last hope (not really - I'll keep looking no matter what)
I am not sure that I understand your question, but all of EF6 CF attributes are in :
System.ComponentModel.DataAnnotations
you can find more here:
System.ComponentModel.DataAnnotations Namespace ()
The attributes dealing with database schema moved to: System.ComponentModel.DataAnnotations.Schema Namespace.
That's why they may appear missing when you upgraded, but just adding that namespace to your code file will get things back working.