Entity Framework - Invalid Column Name '*_ID"

后端 未结 15 1595
长发绾君心
长发绾君心 2020-11-29 21:30

I\'ve narrowed this down to some issue between Code First and Database first EF, but I\'m not sure how to fix it. I\'ll try to be as clear as I can, but I honestly am missin

相关标签:
15条回答
  • 2020-11-29 21:44

    If you have this issue with a navigation property on the same table, you'll have to change the name of our property.

    For example :

    Table : PERSON
    Id
    AncestorId (with a foreign key which references Id named Parent) 
    

    You'll have to change AncestorId for PersonId.

    It seems that EF is trying to create a key ParentId because it couldn't find a table named Ancestor...

    EDIT : This is a fix for Database first !

    0 讨论(0)
  • 2020-11-29 21:48

    Assumptions:

    • Table
    • OtherTable
    • OtherTable_ID

    Now choose one of this ways:


    A)

    Remove ICollection<Table>

    If you have some error related to OtherTable_ID when you are retrieving Table, go to your OtherTable model and make sure you don't have an ICollection<Table> in there. Without a relationship defined, the framework will auto-assume that you must have a FK to OtherTable and create these extra properties in the generated SQL.

    All Credit of this answer is belongs to @LUKE. The above answer is his comment under @drewid answer. I think his comment is so clean then i rewrote it as an answer.


    B)

    • Add OtherTableId to Table

    and

    • Define OtherTableId in the Table in database
    0 讨论(0)
  • 2020-11-29 21:50

    This is a late entry for those (like me) who didn't immediately understand the other 2 answers.

    So...

    EF is trying to map to the EXPECTED name from the PARENT TABLES KEY-REFERENCE...and since...the FOREIGN KEY name was "changed or shortened" in the databases CHILD TABLE relationship...you would get the message above.

    (this fix may differ between versions of EF)

    FOR ME THE FIX WAS:
    ADDING the "ForeignKey" attribute to the model

    public partial class Tour
    {
        public Guid Id { get; set; }
    
        public Guid CategoryId { get; set; }
    
        [Required]
        [StringLength(200)]
        public string Name { get; set; }
    
        [StringLength(500)]
        public string Description { get; set; }
    
        [StringLength(50)]
        public string ShortName { get; set; }
    
        [StringLength(500)]
        public string TourUrl { get; set; }
    
        [StringLength(500)]
        public string ThumbnailUrl { get; set; }
    
        public bool IsActive { get; set; }
    
        [Required]
        [StringLength(720)]
        public string UpdatedBy { get; set; }
    
        [ForeignKey("CategoryId")]
        public virtual TourCategory TourCategory { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-29 21:51

    For me the problem is that I had the table mapped in my app twice - once via Code First, once via Database First.

    Removing either one solves the problem in my case.

    0 讨论(0)
  • 2020-11-29 21:52

    Holy cow - after many hours of trying, I finally figured this out.

    I am doing EF6 database first and I was wondering about the "extent unknown column" error - it was generating table name underscore column name for some reason, and trying to find a nonexistent column.

    In my case, one of my tables had two foreign key references to the same primary key in another table - something like this:

    Animals            Owners
    =======            ======
    AnimalID (PK)      Pet1ID    <- FK to AnimalID
                       Pet2ID    <- also FK to AnimalID
    

    EF was generating some weird column name like Owners_AnimalID1 and Owners_AnimalID2 and then proceeded to break itself.

    The trick here is that these confusing foreign keys need to be registered with EF using Fluent API!

    In your main database context, override the OnModelCreating method and change the entity configuration. Preferably, you'll have a separate file which extends the EntityConfiguration class, but you can do it inline.

    Any way you do it, you'll need to add something like this:

    public class OwnerConfiguration : EntityTypeConfiguration<Owner>
    {
        public OwnerConfiguration()
        {
            HasRequired(x => x.Animals)
                .WithMany(x => x.Owners)  // Or, just .WithMany()
                .HasForeignKey(x => x.Pet1ID);
        }
    }
    

    And with that, EF will (maybe) start to work as you expect. Boom.

    Also, you'll get that same error if you use the above with a nullable column - just use .HasOptional() instead of .HasRequired().


    Here's the link that put me over the hump:

    https://social.msdn.microsoft.com/Forums/en-US/862abdae-b63f-45f5-8a6c-0bdd6eeabfdb/getting-sqlexception-invalid-column-name-userid-from-ef4-codeonly?forum=adonetefx

    And then, the Fluent API docs help out, especially the foreign key examples:

    http://msdn.microsoft.com/en-us/data/jj591620.aspx

    You can also put the configurations on the other end of the key, as described here:

    http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx.

    There's some new problems I'm running into now, but that was the huge conceptual gap that was missing. Hope it helps!

    0 讨论(0)
  • 2020-11-29 21:55

    For me cause of this behavior was because of issue with defined mapping with Fluent API. I had 2 related types, where type A had optional type B object, and type B had many A objects.

    public class A 
    {
        …
        public int? BId {get; set;}
        public B NavigationToBProperty {get; set;}
    }
    public class B
    {
        …
        public List<A> ListOfAProperty {get; set;}
    }
    

    I had defined mapping with fluent api like this:

    A.HasOptional(p=> p.NavigationToBProperty).WithMany().HasForeignKey(key => key.BId);
    

    But the problem was, that type B had navigation property List<A>, so as a result I had SQLException Invalid column name A_Id

    I attached Visual Studio Debug to EF DatabaseContext.Database.Log to output generated SQL to VS Output->Debug window

    db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
    

    And generated SQL had 2 relations from B table -> one with correct id and other with the A_Id

    The issue for the problem was, that I did not add this B.List<A> navigation property into mapping.

    So this is how in my case correct mapping had to be:

    A.HasOptional(p=> p.NavigationToBProperty).WithMany(x => x.ListOfAProperty).HasForeignKey(key => key.BId);
    
    0 讨论(0)
提交回复
热议问题