EF6:复合主键字段作为外键(ALTER TABLE 语句与 FOREIGN KEY 约束冲突)

EF6: Composite Primary Key Field as Foreign Key (ALTER TABLE statement conflicted with the FOREIGN KEY constraint)

我正在尝试将复合主键中的一个字段用作链接到另一个实体的外键。

public class Security
{
    [Key]
    [MaxLength( 20 )]
    public string Symbol { get; set; }
}

public class Price
{
    [Key, Column( Order = 1 )]
    [MaxLength( 20 )]
    [Required]
    public virtual string Symbol { get; set; }

    [Key, Column( Order = 2 )]
    public DateTime AsOf { get; set; }

    [ForeignKey("Symbol")]
    public virtual Security Security { get; set; }
}

当我执行 add-migration/update-database 时,我收到以下错误消息:

ALTER TABLE [dbo].[Prices] 
ADD CONSTRAINT [FK_dbo.Prices_dbo.Securities_Symbol] 
FOREIGN KEY ([Symbol]) 
REFERENCES [dbo].[Securities] ([Symbol]) 
ON DELETE CASCADE 

System.Data.SqlClient.SqlException (0x80131904): The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Prices_dbo.Securities_Symbol". The conflict occurred in database "FitchTrust", table "dbo.Securities", column 'Symbol'.

仅供参考,我在最初创建价格后将证券 属性 添加到价格。不知道这是否会导致问题。

是否可以将复合主键中的一个字段也用作外键?如果是这样,我该如何配置(最好通过注释,但流利 API 也可以)。

这是一个 Sql 错误,它与现有数据有关。这意味着新外键引入的引用完整性已经被破坏,即 dbo.Prices.Symbol 中至少有一个 Symbol 值在 dbo.Securities.Symbol 中不存在。找到罪魁祸首并将该行添加到 dbo.Securities,或将其从 dbo.Prices

中删除

查找:

SELECT * 
FROM dbo.Prices p
WHERE NOT EXISTS
(SELECT 1 
 FROM dbo.Securities s
 WHERE s.Symbol = p.Symbol);

插入证券(您可能需要从其他地方获取其他列)

INSERT INTO dbo.Securities(Symbol)
  SELECT p.Symbol
  FROM dbo.Prices p
  WHERE NOT EXISTS
    (SELECT 1 
     FROM dbo.Securities s
     WHERE s.Symbol = p.Symbol);

或从价格中删除:

DELETE
FROM dbo.Prices p
WHERE NOT EXISTS
(SELECT 1 
 FROM dbo.Securities s
 WHERE s.Symbol = p.Symbol);