简体   繁体   中英

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. 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

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.

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