简体   繁体   English

C#->实体框架6.1.3->复合可为空的外键字符串

[英]C# -> Entity Framework 6.1.3 -> Composite nullable foreign key string

I'm integrating against an external system where they use a lot of composite keys and often strings . 我正在与一个外部系统集成,在该外部系统中它们使用许多复合键,并且经常使用strings I'm now facing a problem where I need to make a composite foreign key nullable . 我现在面临一个需要使复合外键为nullable If the value would be an int i could just mark it as nullable with int? 如果值是一个int我可以用int?将其标记为可为空int? but this is not possible here. 但这在这里是不可能的。 I think I have to use fluent api but if it is possible with data annotations that is the preferred way. 我认为我必须使用流利的api,但如果可以的话,最好使用数据注释。 To make it even harder the first part of the foreign key is also used as the first part for the primary key and thus can not be nullable. 更难的是,外键的第一部分也用作主键的第一部分,因此不能为空。

BillCurrency and DisbCurrency for FeeCalculation are the keys that needs to be nullable below. BillCurrencyDisbCurrencyFeeCalculation有需要可空下键。 The models created are valid apart from the nullable part. 除了可为空的部分以外,创建的模型是有效的。

The obvious exception message: 明显的异常消息:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.FeeCalculations_dbo.ExchangeRates_BusinessSystemId_BillCurrency". INSERT语句与FOREIGN KEY约束“ FK_dbo.FeeCalculations_dbo.ExchangeRates_BusinessSystemId_BillCurrency”冲突。 The conflict occurred in database "Project.Database", table "dbo.ExchangeRates". 数据库“ Project.Database”的表“ dbo.ExchangeRates”中发生了冲突。 The statement has been terminated. 该语句已终止。

public class FeeCalculation
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string BusinessSystemId { get; set; }

    [Key, Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CaseId { get; set; }

    public string BillCurrency { get; set; }

    [ForeignKey("BusinessSystemId,BillCurrency")]
    public virtual ExchangeRate BillCurrencyObject { get; set; }

    public string DisbCurrency { get; set; }

    [ForeignKey("BusinessSystemId,DisbCurrency")]
    public virtual ExchangeRate DisbCurrencyObject { get; set; }

}

public class ExchangeRate
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string BusinessSystemId { get; set; }

    [Key, Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string ForeignCurrency { get; set; }

    public string HomeCurrency { get; set; }

    public DateTime EffectiveDate { get; set; }

    public double Rate { get; set; }
}

原来,模型没有问题,这是一个FeeCalculation值已损坏,并试图插入ExchangeRate不存在的键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM