簡體   English   中英

EF7 MVC6的實體關系

[英]Entity Relations for EF7 MVC6

我的目標是將EF7與MVC6 [BETA2]結合使用,以列出許多書架和每個書架上的書數。

使用正確的表關系正確創建了數據庫模式。 我可以成功地將包括外鍵關系的書架和書籍添加到數據庫中(請參見下面的代碼)。

當我測試應該顯示每個書架上的書數的索引頁時,我沒有收到書數數據,也沒有錯誤。 現有的實體財產圖書上無人居住與圖書實體因此計數為空(見下面的代碼)。

在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>
}
....

看看Entity Framework中的ICollection Vs List 我覺得使用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);
}

我發現的是,EF不會立即將相關的子對象填充到父對象中。 例如,myShelf.Books將為空,直到填充到控制器操作功能中為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM