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.
Related
I'm new, excuse my ignorance.
I have this class:
public class Genre
{
public int Id { get; set; }
[Required]
[StringLength(40)]
[Index(IsUnique = true)] //-----------------------> new change
public string Name{ get; set; }
}
In my first migration called Initial, I forgot the [Index(IsUnique = true)] attribute which makes the Name field unique. So now I want to update my database model for this change to take effect.
I installed the package using System.ComponentModel.DataAnnotations.Schema; to be able to use the unique property.
The commands I ran were:
EntityFrameworkCore\Add-Migration Initial
EntityFrameworkCore\update-database
Apparently I can't do something like:
EntityFrameworkCore\Add-Migration change_attribute_name
EntityFrameworkCore\update-database
to update the database model and that I updated the unique attribute on the Name field which is what I am doing.
I would like to update the model of my database, with the new changes. How can I do it? and what is the best way?
Note: my SQL Server database has no data yet.
Maybe I've been doing fine, you know why the unique attribute is not added in my database model?
(In Spanish Genero=Genre and Nombre=Name)
EDIT
In EF core, you need to apply the unique index in the following way using Fluent API in your ApplicationDbContext.cs file:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Genre>()
.HasIndex(u => u.Name)
.IsUnique();
}
Since as you mentioned, you do not have any data in the database yet, you can revert all your applied migration by using
Update-Database -Migration 0
the -Migration 0 indicates that you want to un-apply all the migrations.
Then you can remove your generated migration using
Remove-Migration
And finally, add migration again using new changes by
Add-Migration Initial
Change the model an try adding migration
Add migration yourmigration name
And then run
Update database
Command this will work for you for sure
I'm building an Asp.net MVC5 + EF6 solution with 3 projects.
I have enabled automatic migration in my project.
The below diagram shows my project structure.
I have a main project and two sub projects.
I have a BaseContext in a main project.
Sub project has their own context classes which derives from
BaseContext.
All above contexts are connecting to one database.
Models:
A Model in Project2
public class Product
{
[Key]
public int ProductId {get;set;}
...
}
A Model in Project3
public class Order
{
[Key]
public int OrderId {get;set;}
[ForeignKey("Product")]
public int ProductId {get;set}
public virtual Product Product;
...
}
An property from Project3 entity (Order.ProductId) references a property from Project2 entity (Product.ProductId) as a foreign key reference.
When I run update-databasecommand in project 1 & 2 everything is going well.
But when run update-database command in project 3 It gives an error:
There is already an object named 'Product' in the database.
Right now I'm using update-database -script command to generate script and manually altering the script. But when project grows, it becomes a difficult task to alter sql scripts each and every time.
I ignored the Product entity by adding modelBuilder.Ignore<Product>() inorder to skip table creation for Productentity, in Project3, but it's ignores the entire relationship.
How can I solve this issue?
You can't do this. One context == one database. When you run a migration against a database for a particular context, it will be based on that context, and will remove any non-applicable tables or try to drop and recreate the database.
You should move all your entities into a class library, along with a single instance of a context that includes them all. Then, you can migrate against the class library and simply reference in your other projects.
Alternatively, you can sort of do what you want by going with an existing database approach. Essentially, you turn off migrations entirely on your base context, and then each sub context can then only include the entities that belong to it. However, you're going to be completely responsible for managing the database, yourself, at that point.
public class BaseContext : DbContext
{
public BaseContext()
: base("ConnectionString")
{
Database.SetInitializer<BaseContext>(null);
}
}
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've been banging my head all day long. I'm new to MVC 5 (MVC and ASP.NET in general) and I can't figure out how do I add an extra table to my current Database (created using CodeFirst approach), and read its content.
Heck, I don't know how to read the other columns I have in the AspNetUsers Table from Identity.
Would someone kindly tell me how this is done? Thanks a million
Edit:
Ok. So I have been tirelessly looking for a solution, and I've come across 35% of it.
I've stumbled upon a book called "Getting Started with Entity Framework 6 Code First using MVC 5 with Tom Dykstra"
Now I know that for creating a table you just create a class under the Model folders, and use a DbSet<> command where you had applied the DbContext call.
Now, what's the problem here? I started from a blank template, since that is the suggestion from "Pro ASP.NET MVC 5" from Adamn Freeman, and I don't want Google, Facebook Authentication.
I have been able to populate the defacto AspNetUsers table with custom fields, and insert Data into it.
What I want to with it, is to create a relational table with a foreign key which should reside in the defacto AspNetUsers table, and I don't how to do it.
Create the entity class (new table). You must specify an attribute as the primary key that should be named (CLASSNAME)ID Ex:
public class Product
{
public int ProductID { get; set; }
public string PropriedadeTeste { get; set; }
}
Map this entity in your implementation of DbContext. This means that Products table will contain Product objects:
public class EFDbContext : DbContext
{
public EFDbContext() : base("DatabaseName") { }
public DbSet<Product> Products { get; set; }
}
Enable migrations in your project (in the Package Manager Console)
Enable-Migrations -ProjectName SportStore.Domain -ContextTypeName ENTER_NAMESPACE_HERE.EFDbContext
Generate the migration - in this example, it will be generated a file named something like 201409172255007_Product.cs, in the Migrations folder:
Add-Migration -ProjectName PROJECT_NAME Product
Update the database:
Update-Database -ProjectName PROJECT_NAME -TargetMigration Product
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.