简体   繁体   中英

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 . I'm now facing a problem where I need to make a composite foreign key nullable . If the value would be an int i could just mark it as nullable with 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. 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. 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". The conflict occurred in database "Project.Database", table "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不存在的键。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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