【发布时间】:2018-09-10 13:14:05
【问题描述】:
考虑以下类:
public class Pie
{
public int Id { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public ICollection<Pie> Pies { get; set; }
}
我有以下来自硬编码文件的数据:
public class MockPieRepository : IPieRepository
{
private readonly ICategoryRepository _categoryRepository = new MockCategoryRepository();
private List<Pie> pies = new List<Pie>() {
new Pie { Id = 1, Name = "Apple Pie", Price = 12.95M, IsPieOfTheWeek = true, ShortDescription = "Yummy Apple Pie", LongDescription = "Lengthy apple pie", ImageThumbnailUrl = "images/thumbs/apple.jpg", ImageUrl = "images/apple.jpg", CategoryId = 1},
new Pie { Id = 2, Name = "Rhubarb Pie", Price = 11.95M, IsPieOfTheWeek = false, ShortDescription = "Yummy Rhubarb Pie", LongDescription = "Lengthy Rhubarb pie", ImageThumbnailUrl = "images/thumbs/Rhubarb.jpg", ImageUrl = "images/Rhubarb.jpg", CategoryId = 1},
new Pie { Id = 3, Name = "Cheesecake", Price = 8.95M, IsPieOfTheWeek = false, ShortDescription = "Yummy Cheesecake Pie", LongDescription = "Lengthy Cheesecake pie", ImageThumbnailUrl = "images/thumbs/Cheesecake.jpg", ImageUrl = "images/Cheesecake.jpg", CategoryId = 2},
new Pie { Id = 4, Name = "Chocolate Cake", Price = 4.95M, IsPieOfTheWeek = false, ShortDescription = "Yummy Chocolate Pie", LongDescription = "Lengthy Chocolate pie", ImageThumbnailUrl = "images/thumbs/Chocolate.jpg", ImageUrl = "images/Chocolate.jpg", CategoryId = 3},
new Pie { Id = 5, Name = "Mince Beef", Price = 6.99M, IsPieOfTheWeek = false, ShortDescription = "Yummy Mince Beef Pie", LongDescription = "Lengthy Mince Beef pie", ImageThumbnailUrl = "images/thumbs/Beef.jpg", ImageUrl = "images/Beef.jpg", CategoryId = 3}
};
public IEnumerable<Pie> GetPies()
{
return pies.OrderBy(p => p.Id);
}
public Pie GetPieById(int pieId)
{
return pies.FirstOrDefault(p => p.Id == pieId);
}
}
public class MockCategoryRepository : ICategoryRepository
{
public IEnumerable<Category> Categories {
get {
return new List<Category>
{
new Category { CategoryId = 1, CategoryName = "Fruit Pies", Description = "All fruity pies"},
new Category { CategoryId = 2, CategoryName = "Cheesecakes", Description = "Cheesecakes to make your heart sing"},
new Category { CategoryId = 3, CategoryName = "Seasonal Pies", Description = "Christmas, Halloween or Spring"}
};
}
}
}
当我尝试从 @pie.Category.CategoryName 获取 CategoryName 时,该值为 null。显然我在尝试从 Pie 导航到 Category 时做错了,但谁能告诉我它是什么?
谢谢。
【问题讨论】:
-
我在你的代码中没有看到
@pie.Category.CategoryName。 -
我假设您假设通过引用类别(例如通过设置
CategoryId = 1),类别会自动应用于Pie,但事实并非如此。您肯定必须自己将具有该 ID 的类别应用到Pie。类似myPie = new Pie { Category = getCategoryById(categoryId) }。 -
首先
@pie是什么?有错误吗?还有什么? -
@HimBromBeere 是的,这就是我的意思。以前我使用过带有实体框架的数据库,并且能够在饼图和类别之间建立关联。显然这并没有像我预期的那样发生在这里。没问题。感谢您抽出宝贵时间
标签: c# asp.net-core-2.1 navigation-properties