我尝试将一个小应用程序迁移到Entity Framework Core但我无法获得多对多的工作关系。
首先是我的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; }
}
我的DbContext是
modelBuilder.Entity()。HasKey(currency =&gt; new { currency.CountryId,currency.CurrencyId}); modelBuilder.Entity() .HasOne(pt =&gt; pt.Country) .WithMany(p =&gt; p.CountryCurrencies) .HasForeignKey(pt =&gt; pt.CountryId);
modelBuilder.Entity<CountryCurrency>() .HasOne(pt => pt.Currency) .WithMany(t => t.CountryCurrencies) .HasForeignKey(pt => pt.CurrencyId);
现在当我添加货币时,例如
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);
所以当我现在在我的测试中检索数据时,我得到了这个代码
Country = context.Countries.Include(country => country.CountryCurrencies).First();
我无法获取ID设置的货币,但财产不是......
答案 0 :(得分:3)
您还必须包括货币实体,而不仅仅是加入实体
Country = context.Countries
.Include(country => country.CountryCurrencies)
.ThenInclude(e => e.Currency)
.First();