0
votes

I try to migrate a small application to Entity Framework Core but I cant get the many to many relation to work. First my Entities

public class Currency : Entity<int>, IMayHaveUser
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string Symbol { get; set; }
    public virtual List<CountryCurrency> CountryCurrencies { get; set; }
    public bool IsUserDefined => User != null;
    [ForeignKey("UserId")]
    public virtual User User { get; set; }
    public long? UserId { get; set; }
}
public class Country : Entity<int>, IMayHaveUser 
{
    public string Iso2Code { get; set; }
    public virtual ICollection<Era> Eras { get; set; }
    public string Name { get; set; }
    public virtual List<CountryCurrency> CountryCurrencies { get; set; }
    [NotMapped]
    public bool IsUserDefined => User != null;
    [ForeignKey("UserId")]
    public virtual User User { get; set; }
    public long? UserId { get; set; }
}
public class CountryCurrency : Entity<Guid>
{
    public int CountryId { get; set; }
    public Country Country { get; set; }
    public int CurrencyId { get; set; }
    public Currency Currency { get; set; }
}

and my DbContext is

modelBuilder.Entity().HasKey(currency => new { currency.CountryId, currency.CurrencyId }); modelBuilder.Entity() .HasOne(pt => pt.Country) .WithMany(p => p.CountryCurrencies) .HasForeignKey(pt => pt.CountryId);

    modelBuilder.Entity<CountryCurrency>()
        .HasOne(pt => pt.Currency)
        .WithMany(t => t.CountryCurrencies)
        .HasForeignKey(pt => pt.CurrencyId);

now when I add a currency for example

  Currency currency;
        Country country;
        CountryCurrency countryCurrency;

        currency = new Currency();
        currency.Id = i++;
        currency.User = null;
        currency.Code = "ETB";
        currency.Name = "Ethiopian Birr";
        currency.Symbol = "Br";

        country =
            this._context.Countries.FirstOrDefault(
                country1 => country1.Iso2Code == "ET");

        if (country != null)
        {
            currency.CountryCurrencies = new List<CountryCurrency>();
            countryCurrency = new CountryCurrency();
            countryCurrency.Country = country;
            countryCurrency.Currency = currency;
            currency.CountryCurrencies.Add(countryCurrency);
            this.InitialCurrencies.Add(currency);
        }
        this._context.Currencies.Add(currency);

so when now I'm retrieve the data in my test I get this with this code

Country = context.Countries.Include(country => country.CountryCurrencies).First();

Debugger

I can't get the currency the id is set but the property not...

1

1 Answers

3
votes

You have also to include the currency entity, not just the join entity

Country = context.Countries
    .Include(country => country.CountryCurrencies)
        .ThenInclude(e => e.Currency)
    .First();