我有两种型号,Pizza和Topping。每个披萨都可以有很多配料。
当我尝试访问每个Pizzas浇头时,尽管我的映射表有多个记录,但它总是说计数为0。
但是,我可以获得与Toppings相关的Pizzas(我不想这样做 - 我猜它出于某种原因是错误的方式)。
型号:
public class Pizza
{
public int PizzaId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Size { get; set; }
public string Status { get; set; }
public virtual ICollection<Topping> PizzaToppings { get; set; }
}
public class Topping
{
public int ToppingId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Size { get; set; }
public string Status { get; set; }
public virtual ICollection<Pizza> PizzasOn { get; set; }
}
public class EFDbContext : DbContext
{
public DbSet<Pizza> Pizzas { get; set; }
public DbSet<Topping> Toppings { get; set; }
}
查看:
<p>Pizza Topping Count: @Model.PizzaToppings.Count()</p>
返回0。
控制器:
public ViewResult ViewPizza(Pizza pizza)
{
Pizza pizzaDetails = pizza;
return View(pizzaDetails);
}
答案 0 :(得分:1)
您必须明确加载Toppings,如下所示:
var pizzas = db.Pizzas.Include("PizzaToppings");
var pizza = pizzas.Where()... // select your specific pizza
答案 1 :(得分:0)
我在控制台应用程序中测试了你的模型它工作正常。以下是我的代码:
PizzaContext context = new PizzaContext();
Pizza veggiDelite = new Pizza { Name = "Veggi Delite" };
Topping pineapple = new Topping { Name = "Pineapple" };
Topping chicken = new Topping { Name = "Chicken" };
Pizza supremeChickenPizza = new Pizza { Name = "Supreme Chicken Pizza" };
veggiDelite.PizzaToppings = new Collection<Topping> { new Topping { Name = "Jalepeeno" }, pineapple };
supremeChickenPizza.PizzaToppings = new Collection<Topping> { pineapple };
chicken.PizzasOn = new Collection<Pizza> { supremeChickenPizza };
context.Pizzas.Add(veggiDelite);
context.Toppings.Add(chicken);
context.SaveChanges();
foreach (Topping topping in context.Pizzas.SelectMany(p => p.PizzaToppings))
{
Console.WriteLine(topping.Name);
}
Console.ReadLine();
输出:
看到您的代码后,我建议您调查将Pizza object
传递给您的操作方法的来源。披萨对象可能会丢失上下文(例如,您正在使用Web服务来获取此Pizza object
),如果是这样,则可能会遇到此类问题。