In our previous example, we learnt code first mode where in the database is created based on the Model class signature. Database First model is a way to create tables objects, relations, etc in database first and incorporate the same in Entity Framework.
BookStoreModel.cs
public class BookStoreModel : DbContext
{
public string connString = @"Data Source=DESKTOP-TAE8O0I\SQLEXPRESS;Initial Catalog=BooksDB;Integrated Security=True;Pooling=False";
public DbSet<Book> Book { get; set; }
public DbSet<Authors> Authors { get; set; }
public BookStoreModel()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(connString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>().ToTable("MyBookTable");
}
}
In the model, I created property for Authors Table and will then create a class Author.cs to hook up MyAuthorTable from the Database to the Authors class.
public DbSet<Authors> Authors { get; set; }
Authors.cs
[Table("MyAuthorTable")]
public class Authors
{
[Key]
public int AuthorID { get; set; }
public string AuthorName { get; set; }
public string AuthorLanguage { get; set; }
public string AuthorCountry { get; set; }
}
Once we have our model class ready and the database table hooked up with EF object, we will show it on the screen using MVC’s HomeController and view page. We are sending the list of authors in a view bag to the MVC’s view below
HomeController.cs
public IActionResult Index()
{
List<Authors> authors = new List<Authors>();
Book book = new Book();
book.BookName = "Learn EF Core";
book.BookAuthor = "Naved";
BookStoreModel model = new BookStoreModel();
model.Book.Add(book);
model.SaveChanges();
authors = model.Authors.ToList();
ViewBag.LstAuthors = authors;
return View();
}
We are sending the list of authors in a view bag to the MVC’s view below
authors = model.Authors.ToList();
ViewBag.LstAuthors = authors;
Index.cshtml
@model IEnumerable<BookStoreModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<table class="table table-bordered table-responsive">
<tr>
<th>ID </th>
<th>Name </th>
<th>Language </th>
<th>Country</th>
</tr>
@foreach (var d in ViewBag.LstAuthors)
{
<tr>
<td>@d.AuthorID</td>
<td>@d.AuthorName</td>
<td>@d.AuthorLanguage</td>
<td>@d.AuthorCountry</td>
</tr>
}
</table>
UI:
