简体   繁体   English

在一个类中具有两个相同类型的导航属性

[英]Having two navigation properties of the same type in a class

Very similar to this question 此问题非常相似

I've got a class: 我有一堂课:

public class RateOfExchange
{
    public int RateOfExchangeID { get; set; }
    public int CurrencyID { get; set; }
    public int BaseCurrencyID { get; set; }
    public virtual Currency Currency { get; set; }
    public virtual Currency BaseCurrency { get; set; }
}

Using EF 6 Code First, I have no errors creating the model and seeding this table but both the Currency and BaseCurrency navigation properties are null when the application is run. 首先使用EF 6代码,我没有错误创建模型并为该表添加种子,但是运行应用程序时Currency和BaseCurrency导航属性均为null。 The advice in the above question is to remove the delete on cascade configuration from each relationship which results in an exception being thrown on seeding - I don't think I'm setting up my relationship properly. 上面问题中的建议是从每个关系中删除级联配置上的删除,这会导致播种时引发异常-我认为我没有正确建立我的关系。

(as I'm writing this I've just figured out the syntax for this particular relationship, I'll post as an answer) (在撰写本文时,我只是想出了这种特殊关系的语法,我将作为答案发布)

Here is the code you need in your OnModelCreating method 这是您在OnModelCreating方法中所需的代码

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<RateOfExchange>()
        .HasRequired(r => r.Currency)      // at least one entry in Currency
        .WithMany()                        // many RateOfExchange entries 
        .HasForeignKey(r => r.CurrencyID)  // use this RateOfExchange member as they foreign key
        .WillCascadeOnDelete(false);            
    modelBuilder.Entity<RateOfExchange>()
        .HasRequired(r => item.BaseCurrency)
        .WithMany()
        .HasForeignKey(r => item.BaseCurrencyID)
        .WillCascadeOnDelete(false);
}

The answer quoted in the question pointed me in the right direction, it was just a matter of applying the syntax correctly to my table structure. 问题中引用的答案为我指明了正确的方向,这只是将语法正确应用于表结构的问题。 I also needed to specify the foreign key which wasn't mentioned. 我还需要指定未提及的外键。

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

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