I am currently making an application that requires linking a Soap Formula to it’s Oils for later calculations.
The Join Class is called FormulaOil and has both ids
public int FormulaId { get; set; }
public Formula? Formula { get; set; }
public int OilId { get; set; }
public Oil? Oil { get; set; }
public double Percentage { get; set; }
public double Weight { get; set; }
and on Formula I have these Navigation Properties
public virtual ICollection<FormulaOil> FormulaOils { get; set; } = new List<FormulaOil>();
public virtual IEnumerable<Oil> Oils { get; set; } = new List<Oil>();
for Oil similarly
public virtual ICollection<FormulaOil> FormulaOils { get; set; } = new List<FormulaOil>();
public virtual ICollection<Formula> Formulas { get; set; } = new List<Formula>();
This to me seems to be matching the instruction given on the many to many section of the docs of entity framework https://learn.microsoft.com/en-us/ef/core/modeling/relationships/many-to-many
Yet when unit tested I seem to not be able to get the results correctly and the Oils navigation remains empty. Unit testing is done with an inMemoryDatabase.
private readonly AppDbContext ctx;
public UnitTest1()
{
var options = new DbContextOptionsBuilder<AppDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
ctx = new AppDbContext(options, TestAuthenticatedUser.Instance);
}
[Fact]
public void EnsureOilListReflectsWhatIsInOilIngrients()
{
var oil = new Oil()
{
Name = "Oil 1",
};
ctx.Oils.Add(oil);
var formula = new Formula() {
Name = "Formula 1"
};
ctx.Formulas.Add(formula);
ctx.SaveChanges();
var oilIngrefient = new FormulaOil()
{
OilId = oil.Id,
FormulaId = formula.Id,
};
ctx.OilIngredients.Add(oilIngrefient);
ctx.SaveChanges();
formula = ctx.Formulas.Include(x => x.FormulaOils).First();
Assert.Equal(formula!.FormulaOils.Count, formula.Oils.Count());
}
Am I missing some details in this?
Massine Mouha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.