简体   繁体   中英

Entity Framework 6.2 Code First errors

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;}  
} 
  1. add-migration not found entity framework on project. But I installed it already. Besides, I deleted all packages folder. However still continue same exception.

  2. 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.

  1. 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

  1. 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.

  2. Try run command Install-Package EntityFramework -Version 6.2.0 -Project {{EFProjectName}} to reinstall package and reference it correctly.

  3. 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.

  4. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM