我的目标是使用EF7和MVC6 [BETA2]列出一些书架和每个书架上的书籍数量。
使用正确的表关系正确创建数据库模式。我可以成功地将数据库和书籍添加到数据库中,包括外键关系(参见下面的代码)。
当我测试应在每个书架上显示书籍数量的索引页面时,我没有收到任何书籍计数数据且没有错误。在 Shelf 实体中,属性 Books 仍未使用 Book 实体填充,因此计数为null(请参阅下面的代码)。
在EF7中我需要编写代码来填充 Shelf.Books ,还是应该在EF7中自动发生?
BookShelf.cs
namespace MyApp.Models
{
public class Shelf
{
public int ShelfId { get; set; }
public string Name { get; set; }
public virtual List<Books> Books { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Name { get; set; }
public int ShelfId { get; set; }
public Shelf Shelf{ get; set; }
}
}
ApplicationDbContext.cs
namespace MyApp
{
public class ApplicationDBContext
{
public DbSet<Shelf> Shelf { get; set; }
public DbSet<Book> Book { get; set; }
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Shelf>().Key(s => s.ShelfId);
builder.Entity<Book>().Key(b => b.BookId);
builder.Entity<Shelf>()
.OneToMany(s => s.Book)
.ForeignKey(k => k.ShelfId);
base.OnModelCreating(builder);
}
}
ShelfController.cs
namespace MyApp
{
private ApplicationDBContext db;
public BuildingsController(ApplicationDBContext context)
{
db = context;
}
// GET: Shelves
public async Task<IActionResult> Index()
{
return View(await db.Shelves.ToListAsync());
}
}
Index.cshtml
...
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Books.Count)
</td>
</tr>
}
....
答案 0 :(得分:0)
看看ICollection Vs List in Entity Framework。我觉得使用List<>
的EF7的小例子是不正确的(很难想象EF7的最佳做法是从ICollection<>
更改为List<>
,这通常是非常糟糕的做法具体的集合类型作为属性。)
根据你的评论我会改变:
创建视图模型
public class IndexViewModel
{
public IEnumerable<ShelveModel> Shelves { get; set; }
}
public class ShelveModel
{
public string Name { get; set; }
public int BookCount { get ; set; }
}
更新逻辑
// GET: Shelves
public async Task<IActionResult> Index()
{
var model = new IndexViewModel();
model.Shelves = db.Shelves
.Select(s => new
{
Name = s.Name,
BookCount = s.Books.Count()
})
.ToListAsync()
.Select(s => new ShelveModel()
{
Name = s.Name,
BookCount = s.Books.Count()
})
.ToList();
return View(model);
}
答案 1 :(得分:0)
我发现EF不会使用开箱即用的相关子对象填充父对象。例如,myShelf.Books将为空,直到在控制器动作函数中填充。