I use sql management studio 2016

Here is the screen:

enter image description here

Code in View (Index.cshtml):

@model IEnumerable<WebApplication1.Models.Book> @{ Layout = "~/Views/Shared/_Layout.cshtml"; } <div> <h3>РаспродаТа ΠΊΠ½ΠΈΠ³</h3> <table> <tr class="header"> <td><p>НазваниС ΠΊΠ½ΠΈΠ³ΠΈ</p></td> <td><p>Автор</p></td> <td><p>Π¦Π΅Π½Π°</p></td> <td></td> </tr> @foreach (WebApplication1.Models.Book b in Model) { <tr> <td><p>@b.Name</p></td> <td><p>@b.Author</p></td> <td><p>@b.Price</p></td> <td><p><a href="/Home/Buy/@b.Id">ΠšΡƒΠΏΠΈΡ‚ΡŒ</a></p></td> </tr> } </table> </div> 

WebConfig:

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

HomeController:

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

BookContext:

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

In Bd there is data:

enter image description here

Perhaps the fact is that after starting the database is turned off? : enter image description here

  • Change public BookContext() : base("DefaultConnection") to public BookContext() : base("name=BookContext") { } - Vadim Prokopchuk
  • @VadimProkopchuk Thank you! :) - Andrew_Romanuk
  • @AnrewRomanuk, did it work? - Vadim Prokopchuk February
  • Yes. You can answer, I will choose your best answer. - Andrew_Romanuk February

2 answers 2

Change the name of the connection according to the Web.config file

 public BookContext() : base("name=BookContext") { } 

    Pass the objects in the ViewBag

     public class HomeController : Controller { // создаСм контСкст Π΄Π°Π½Π½Ρ‹Ρ… BookContext db = new BookContext(); public ActionResult Index() { // ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΈΠ· Π±Π΄ всС ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρ‹ Book IEnumerable<Book> books = db.Books; // ΠΏΠ΅Ρ€Π΅Π΄Π°Π΅ΠΌ всС ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρ‹ Π² динамичСскоС свойство Books Π² ViewBag ViewBag.Books = books; // Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅ΠΌ прСдставлСниС return View(); } } 

    And then print on page

     @foreach (var b in ViewBag.Books) { <tr> <td><p>@b.Name</p></td> <td><p>@b.Author</p></td> <td><p>@b.Price</p></td> <td><p><a href="/Home/Buy/@b.Id">ΠšΡƒΠΏΠΈΡ‚ΡŒ</a></p></td> </tr> } 

    And you should have a Book class

     public class Book { // ID ΠΊΠ½ΠΈΠ³ΠΈ public int Id { get; set; } // Π½Π°Π·Π²Π°Π½ΠΈΠ΅ ΠΊΠ½ΠΈΠ³ΠΈ public string Name { get; set; } // Π°Π²Ρ‚ΠΎΡ€ ΠΊΠ½ΠΈΠ³ΠΈ public string Author { get; set; } // Ρ†Π΅Π½Π° public int Price { get; set; } } 
    • Eh, it still does not work ( - Andrew_Romanuk