Visual Studio 2015

enter image description here

HomeControllet:

BookContext db = new BookContext(); // GET: Home public ActionResult Index() { return View(db.Books); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } 

Index.cshtml:

 @Model WebApplication4.Models.Book @{ ViewBag.Title = "Index"; Layout = "~/Views/_Layout.cshtml"; } @Model WebApplication4.Models.Book <h2>Книга № @Model.Id</h2> @Html.DisplayForModel() 

Book (Model):

  public class Book { public int Id { get; set; } public string Name { get; set; } public string Author { get; set; } public int Price { get; set; } } 

BookContext (Model):

  public class BookContext :DbContext { public BookContext() : base("BookContext") { } public DbSet<Book> Books { get; set; } public DbSet<Purchase> Purchases { get; set; } } 

WebConfig:

  <add name="BookContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Bookstore.mdf;Integrated Security=True; MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" /> </connectionStrings> 

The database is full of data. What is the problem ?

  • Obviously, in the Index view, you declare the Book class as a model and pass the DbSet<Book> . Try for example like this: db.Books.First() - DreamChild

2 answers 2

 public ActionResult Index() { BookContext db = new BookContext (); Book singleBook = db.Books.Where( b=> b.ID == "1" ).First(); return View(singleBook); } 

    Looks like you are submitting a book collection to View.

     // GET: Home public ActionResult Index() { return View(db.Books); } 

    And in View, you expect one Book , not a collection.