0% found this document useful (0 votes)
2 views7 pages

EF Core Database First MVC Lesson

This document outlines the process of integrating Entity Framework (EF) Core with an ASP.NET Core MVC application using a Database-First approach. It covers key concepts such as Object-Relational Mapping (ORM), how EF Core maps database structures to C# objects, and the use of Dependency Injection to manage DbContext. The document also emphasizes the importance of understanding the existing database schema before creating entity classes and provides practical exercises for applying these concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

EF Core Database First MVC Lesson

This document outlines the process of integrating Entity Framework (EF) Core with an ASP.NET Core MVC application using a Database-First approach. It covers key concepts such as Object-Relational Mapping (ORM), how EF Core maps database structures to C# objects, and the use of Dependency Injection to manage DbContext. The document also emphasizes the importance of understanding the existing database schema before creating entity classes and provides practical exercises for applying these concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lesson: EF Core Database-First + MVC +

Dependency Injection
Learning Objectives
 Explain what an ORM does.
 Explain how EF Core maps relational database data to C# objects.
 Identify tables, columns, primary keys, and foreign keys in an existing SQLite database.
 Manually create EF Core entity classes from an existing database.
 Use Data Annotations to map entities to database structures.
 Create and use a DbContext.
 Register DbContext using Dependency Injection.
 Query an existing SQLite database using LINQ.
 Use related entities through navigation properties.
 Integrate EF Core into an [Link] Core MVC application.
 Understand the purpose of NuGet packages required by EF Core.
 Explain the difference between Database-First and Code-First.

Part 1 — The Problem We Are Solving


 An MVC application can work with C# objects, but real applications need persistent
storage.
 EF Core allows the application to work with persistent relational data.

Part 2 — What Is an ORM?


 ORM means Object-Relational Mapper.
 A relational database works with tables, columns, rows, primary keys, foreign keys, and
relationships. C# works with classes, properties, objects, references, and collections.
 EF Core allows us to work with database data using C# and LINQ. EF Core translates
appropriate LINQ expressions into SQL and sends them to the database.

Part 3 — Database-First vs Code-First


 Code-First starts with C# classes and uses EF Core to create or modify a database.
 Database-First starts with an existing database. You understand its schema, manually
create the C# entity model, and build the application around it.
 For this project, the database already exists. You adapt the application to the existing
database.
Part 4 — Understanding a Database
Before writing an entity, inspect the database. Determine the tables, columns, data types,
primary keys, foreign keys, and nullable columns.

Part 5 — Creating an Entity


A database table can be represented by a C# entity. The following example is intentionally
unrelated to the project database.

Part 6 — Primary Keys


A primary key uniquely identifies a record. The [Key] attribute identifies the property as the
primary key.

Part 7 — Foreign Keys


A foreign key identifies a related record in another table. The FK property represents the
database column and the navigation property represents the related entity.

Part 8 — Navigation Properties


Navigation properties allow EF Core to represent relationships as objects. A related entity
can also expose a collection navigation.

Part 9 — Nullable Relationships


If a foreign-key column permits NULL in the database, the corresponding C# FK and
navigation property should normally be nullable. Do not decide nullability based on
preference; determine it from the database.

Part 10 — Data Annotations


Data Annotations can provide mapping information directly on entity classes. Use an
annotation when it corresponds to the database structure you are modeling.

 EF Core functionality is provided through NuGet packages. A typical application


requires EF Core plus the provider needed for its database.
 Package versions should be appropriate for the project's target .NET and EF Core
versions. You should be able to explain why the packages in your project are present.

Part 11 — NuGet Packages


NuGet is the package management system used by .NET projects. Packages add libraries and
functionality that are not part of the basic project.
For an [Link] Core MVC application using EF Core with SQLite, you need the appropriate
EF Core packages and the SQLite database provider.

Typical package roles:

[Link]
Core EF Core functionality

[Link]
SQLite database provider for EF Core

[Link]
EF Core tooling used by development workflows when required

The exact packages and versions depend on the project's target framework and
requirements. Do not install packages blindly. Understand what each package provides.

NuGet packages are recorded in the project's .csproj file. When another developer clones
the repository, the project can restore those packages.

Part 12 — SQLite
SQLite is a relational database that stores the database in a file. Unlike SQL Server, there is
no separate database server that must be running for a local SQLite database.

For this project, the supplied database is an SQLite file. The application must connect to that
existing file.

Example:

[Link]

The database file contains the existing database structure and records.
The application reads from that file through EF Core's SQLite provider.

The important distinction is that SQLite is the database engine, while EF Core is the ORM
used by the application to work with that database.

Part 13 — [Link] and Connection Strings


[Link] Core applications commonly keep configuration in [Link]. A database
connection string should be stored in configuration rather than hard-coded throughout the
application.

{
"ConnectionStrings": {
"DefaultConnection": "Data Source=[Link]"
}
}
The name DefaultConnection is a configuration key. The application can retrieve it when
registering the DbContext.

[Link]<LibraryContext>(options =>
[Link](
[Link]("DefaultConnection")
));

This connects several concepts together: [Link] provides the connection string,
UseSqlite tells EF Core which database provider to use, and AddDbContext registers the
DbContext with [Link] Core Dependency Injection.

Part 14 — Dependency Injection


Once the DbContext is registered with AddDbContext, [Link] Core's Dependency Injection
container can provide it to controllers.

public class BooksController : Controller


{
private readonly LibraryContext _context;

public BooksController(LibraryContext context)


{
_context = context;
}
}

The controller does not create the DbContext itself. [Link] Core creates and supplies the
registered dependency.

DbContext is EF Core's primary gateway for working with the database.

The application needs to know where the SQLite database is located. Keep the connection
string in configuration rather than scattering it throughout controllers.

[Link] Core can create and provide dependencies such as a DbContext to controllers. The
controller should receive the dependency instead of manually constructing the DbContext.

A controller can receive the DbContext through its constructor.

Part 16 — Querying With LINQ


EF Core supports filtering, sorting, counting, and other LINQ operations against the
database.

Part 17 — Querying Relationships


Navigation properties can be used when querying related data. EF Core can retrieve related
data through the relationships represented by the entity model.
Part 18 — MVC + EF Core
A typical request flows from the browser to a controller, through EF Core to SQLite, back
through the controller, and finally to a Razor View.

Part 19 — The Important Part of Database-First


 When given an existing database, do not start by writing C# classes from memory.
 Inspect the database, identify tables and columns, identify keys and relationships, create
the entities, add appropriate Data Annotations, create the DbContext, configure
Dependency Injection, query the database, and display the results through MVC.
 The database tells you what the model needs to represent.

Part 20 — Practical Exercise


 You are now given an existing SQLite database. Your first task is not to build the MVC
application. Your first task is to investigate.
 For a table you are studying, determine its table name, columns, data types, primary
key, nullable columns, foreign keys, related tables, and relationship types.
 Then manually create its C# entity. Do not use scaffolding. The goal is to practice
translating relational structure into an object model.

Part 21 — Check Your Understanding


 What problem does an ORM solve?
 What does EF Core do between C# and the database?
 If the database already exists, which side is the source of truth in Database-First?
 What makes a property a primary key?
 What is the difference between a foreign-key property such as AuthorId and a
navigation property such as Author?
 Why would an entity have an ICollection<T> navigation property?
 Why should a controller not manually create its own DbContext?
 Where does EF Core fit into the MVC request pipeline?

Final Mental Model


For the project, you are not designing the database. You are learning how to take an existing
relational database and make an [Link] Core MVC application understand and use it.
Core Examples

Entity
[Table("Books")]
public class Book
{
[Key]
public int Id { get; set; }

[Required]
public string Title { get; set; } = [Link];

public int PublishedYear { get; set; }


}

Foreign Key
public int AuthorId { get; set; }

[ForeignKey(nameof(AuthorId))]
public Author Author { get; set; } = null!;

Collection Navigation
public ICollection<Book> Books { get; set; }
= new List<Book>();

Nullable Foreign Key


public int? PublisherId { get; set; }

[ForeignKey(nameof(PublisherId))]
public Publisher? Publisher { get; set; }

DbContext
public class LibraryContext : DbContext
{
public LibraryContext(
DbContextOptions<LibraryContext> options)
: base(options)
{
}

public DbSet<Book> Books { get; set; }


public DbSet<Author> Authors { get; set; }
}
Constructor Injection
public class BooksController : Controller
{
private readonly LibraryContext _context;

public BooksController(LibraryContext context)


{
_context = context;
}
}

LINQ
var books = _context.Books
.Where(b => [Link] >= 2020)
.OrderBy(b => [Link])
.ToList();

Related Data
var books = _context.Books
.Include(b => [Link])
.ToList();

You might also like