EF7 MVC6的实体关系

问题描述 投票:2回答:2

我的目标是使用EF7和MVC6 [BETA2]列出一些书架和每个书架上的书籍数量。

使用正确的表关系正确创建数据库模式。我可以成功地将数据库和书籍添加到数据库,包括外键关系(请参阅下面的代码)。

当我测试应该在每个架子上显示书籍数量的索引页面时,我没有收到任何书籍计数数据而且没有错误。在Shelf实体中,属性Books仍未使用Book实体填充,因此count为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>
}
....
c# asp.net-core entity-framework-core
2个回答
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);
}

0
投票

我发现EF不会使用相关的子对象填充父对象。例如,myShelf.Books将为空,直到填充在控制器动作函数中。

© www.soinside.com 2019 - 2024. All rights reserved.