实体框架数据库更新:外键引用无效列(导航属性)

时间:2013-03-23 19:59:14

标签: asp.net-mvc entity-framework code-first navigation-properties database-update

这应该很简单。

我有客户和项目:

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; }
}

一切正常。在我的Projects表中,我有一个字段:Client_ClientID存储关系。

现在我想在Project上添加一个导航属性到Client:

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

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

当我运行Update-Database时,我收到错误:

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

详细的SQL显示为:

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])

我不确定为什么它在尝试将Client_ClientID重命名为Client_ClientID1之前,在添加约束之前 - 看起来很奇怪?

我出错了什么?

1 个答案:

答案 0 :(得分:0)

ForeignKeyAttribute添加到Project班级。

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; }
}