【发布时间】:2014-05-16 23:44:19
【问题描述】:
我正在使用带有存储库、Code First、Code First 迁移和 Web Api 的实体框架。我有 Town 和 City 类,它们看起来是这样的:
public class Town
{
public int TownId { get; set; }
public int CityId { get; set; }
public string Name { get; set; }
}
public class City
{
public int CityId { get; set; }
public List<Town> Towns { get; set; }
public string Name { get; set; }
public City()
{
Towns = new List<Town>();
}
}
这是我的 DbContext:
public class EFDbContext : DbContext
{
public DbSet<City> Cities { get; set; }
public DbSet<Town> Towns { get; set; }
}
这是我的种子方法[Configuration.cs(迁移文件夹)]
context.Cities.AddOrUpdate(s => s.Name,
new City
{
Name = "Pinar del Río",
Towns = new List<Town>()
{
new Town() {Name = "Consolación del Sur"},
new Town() {Name = "Guane"},
new Town() {Name = "La Palma"},
new Town() {Name = "Los Palacios"},
new Town() {Name = "Mantua"},
new Town() {Name = "Minas de Matahambre"},
new Town() {Name = "Pinar del Río"},
new Town() {Name = "San Juan y Martínez"},
new Town() {Name = "San Luis"},
new Town() {Name = "Sandino"},
new Town() {Name = "Viñales"}
}
}
)
这是城镇表数据(数据库)
表城市数据(数据库)
这是我的仓库
public class EFLocalizationRepository:ILocalizationRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<City> Cities { get { return context.Cities; } }
public List<Town> GetTowns(int cityId)
{
var c = context.Cities.Find(cityId); //here ok
var tws = context.Cities.Find(cityId).Towns; // but here is empty
return tws;
}
}
当我获取城镇时,我得到一个空列表,为什么?
【问题讨论】:
-
你试过 var tws = c.Towns;我想不出你为什么得到一个空列表,但既然你已经得到了你想要的城市,为什么你不尝试得到它的城镇?
-
是的,我做到了。但都是一样的
-
如果你在变量c中设置了断点,然后开始debug,F10,右键c然后QuickWatch。你看到那里的城镇列表了吗?
-
是的,我做到了,但它是空的
-
那看起来很奇怪!既然你得到了正确的城市,但不是它的城镇?当你在这里说好的时,你的意思是 cityId=1 你得到了我们在你的桌子上显示的城市。对吗?
标签: c# asp.net-mvc-4 database-design entity-framework-5 code-first