0

这应该很简单。

我有客户和项目:

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 上添加一个导航属性到客户端:

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

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

当我运行更新数据库时,我收到错误:

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 - 看起来很奇怪?

我怎么了?

4

1 回答 1

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; }
}
于 2013-03-23T22:21:40.600 回答