Web API: strp by step for dot net web api EF
EF:
Entity Framework (EF) is an Object-Relational Mapper (ORM) for .NET. It
allows developers to interact with a database using .NET objects, rather
than writing raw SQL queries.
This EF we can develop ef in our application 2 different ways
[Link] a model class in models folder
🔧 1. Code First
✅ Best for:
Developers who prefer to define the data model using C# classes.
Applications where you don't already have a database.
🧱 How it works:
You define your entities (C# classes), and EF uses them to generate the database schema.
💡 Key Components:
Entity classes (e.g. Student)
A DbContext class
Migrations to create/update the database
✅ Example:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
🏗 2. Database First
✅ Best for:
Applications where a database already exists.
When you're working with legacy databases.
EF will generate:
Entity classes for each table.
A context class that maps to the database.
In booth approaches we gone to use this bellow newget pacages .
public class Student
{
[Key]
[DatabaseGenerated([Link])]
public int SId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
[Link] the
[Link]
[Link]
[Link]
In new get pacage console
[Link] connection string
[Link] to appsettings
{
"Logging": {
"LogLevel": {
"Default": "Information",
"[Link]": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=LAPTOP-292R4EF2\\SQLEXPRESS;Database=Ex1-
ColleageDB;Trusted_Connection=True;Encrypt=True;TrustServerCertificate=True"
},
"AllowedHosts": "*"
}
[Link] context class
public class ColleageDbContext:DbContext
{
DbSet<Student> students { get; set; }
}
This Dbset<>
DbSet<T> represents a collection of all entities in the database of type T.
It maps to a table in your database.
T is typically a class that represents a model or entity.
students { get; set; }
It allows EF to access and manipulate the collection of Student
entities.