Search code examples
asp.net-mvcentity-frameworkcode-firstnavigation-propertiessql-update

Entity Framework Database Update: Foreign Key References Invalid Column (navigation property)


This should be simple.

I have Clients and Projects:

public class Client
{
    public int ClientID { get; set; }
    public string ClientName { get; set; }
    public virtual ICollection<Project> Projects { get; set; }
}

public class Project
{
    public int ProjectID { get; set; }
    public string ProjectName { get; set; }
}

All that is working fine. In my Projects table, I have the field: Client_ClientID storing the relationship.

Now I want to add a navigation property on Project, to Client:

public class Project
{
    public int ProjectID { get; set; }
    public string ProjectName { get; set; }

    // navigation properties
    public virtual Client Client { get; set; }
}

When I run Update-Database, I get the error:

Foreign key 'FK_dbo.Projects_dbo.Clients_Client_ClientID' references invalid column 'Client_ClientID' in referencing table 'Projects'

The verbose SQL is showing as:

EXECUTE sp_rename @objname = N'dbo.Projects.Client_ClientID', @newname = N'Client_ClientID1', @objtype = N'COLUMN'
ALTER TABLE [dbo].[Projects] ADD CONSTRAINT [FK_dbo.Projects_dbo.Clients_Client_ClientID] FOREIGN KEY ([Client_ClientID]) REFERENCES [dbo].[Clients] ([ClientID])

I'm not sure why it's trying to rename Client_ClientID to Client_ClientID1, before adding a constraint on it - seems odd?

What am I getting wrong?


Solution

  • Add the ForeignKeyAttribute to your Project class.

    public class Project
    {
        public int ProjectID { get; set; }
        public string ProjectName { get; set; }
    
        [ForeignKey("Client")]
        public int ClientID { get; set; }
        public virtual Client Client { get; set; }
    }