DbContext
Models
folder, but ideally should be in a separate abstraction/repository folder (for example Repositories
): base(options)
DbSet
property for each resourcepublic class ContactsContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
public ContactsContext(DbContextOptions<ContactsContext> options) : base(options) { }
}
OnModelCreating
methodContact
with columns Id
, Name
and Email
will be created:public class ContactsContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
public ContactsContext(DbContextOptions<ContactsContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>().ToTable("Contact");
}
}
Id
, Name
and Email
columns:public class ContactsContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
public ContactsContext(DbContextOptions<ContactsContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Contact>().HasData(
new Contact { Id = 1, Name = "Johannes Kantola", Email = "johkant@example.com" },
new Contact { Id = 2, Name = "Rene Orosz", Email = "rene_king@example.com" }
);
}
}
Program.cs
, add the context to services with AddDbContext
methodNpgsql
as in the package nameoptions.UseNpgsql
as a connection string:services.AddDbContext<ContactsContext>(options => options.UseNpgsql(
@"Server=PostgreSQL 12;Host=localhost;Port=5432;Username=postgres;Password=1234;Database=contacts"));
services.AddScoped<IContactRepository, ContactRepository>();
services.AddControllers().AddNewtonsoftJson();
Add-Migration <name>
to the console, for exampleAdd-Migration InitialMigration
Update-Database
to the console
ModelBuilder
optionsContacts
table in this example) should show up in the database. You can check it up e.g. in pgAdmin.Continue working on the CourseAPI.
course_db
in pgAdmin or psqlDbContext
for the courses. Name it CoursesContext
, and add a DbSet
of type Course
to it, named Courses
OnModelCreating
method to the context and add a couple of courses with some starting values to the modelBuilder
CoursesContext
to the services in Program.cs
with a connection string pointing to course_db
Course
table with the starting values has appeared to the databaseDbContext
is added to services, it can be accessed from any other service, such as the repositoryDbSet
for each model in your project, CRUD operations can be applied to the database from the repository with LINQ and DbSet
methods
Add()
Update()
Remove()
DbSet
, update the changes to the database with the DbContext.SaveChanges()
methodDbContext
to your repositories as you would any other service:public class ContactRepository : IContactRepository
{
private readonly ContactsContext _context;
public ContactRepository(ContactsContext context)
{
_context = context;
}
//...
}
public class ContactRepository : IContactRepository
{
private readonly ContactsContext _context;
public ContactRepository(ContactsContext context) { ... }
public Contact GetContact(int id) =>
_context.Contacts.FirstOrDefault(c => c.Id == id);
public List<Contact> GetContacts() =>
_context.Contacts.ToList();
}
public class ContactRepository : IContactRepository
{
private readonly ContactsContext _context;
public ContactRepository(ContactsContext context) { ... }
// Read operations
// ...
public void AddContact(Contact contact)
{
_context.Contacts.Add(contact);
_context.SaveChanges();
}
}
public class ContactRepository : IContactRepository
{
private readonly ContactsContext _context;
public ContactRepository(ContactsContext context) { ... }
// Read & create operations
// ...
public void UpdateContact(int id, Contact newContact)
{
var contact = GetContact(id);
contact.Email = newContact.Email;
contact.Name = newContact.Name;
_context.Contacts.Update(contact);
_context.SaveChanges();
}
}
public class ContactRepository : IContactRepository
{
private readonly ContactsContext _context;
public ContactRepository(ContactsContext context) { ... }
// Read, create & update operations
// ...
public void DeleteContact(int id)
{
_context.Contacts.Remove(GetContact(id));
_context.SaveChanges();
}
}
Continue working on CourseAPI.
CourseRepository
to create, read, update and delete from the database instead of the locally stored list of coursesDbContext
for the databaseDbContext
to servicesAdd-Migration
& Update-Database
Account
Contact
directly having an Email
, it will have an Account
insteadAccount
holds the information about the Email
, as well as a Description
about the nature of the account (personal, work, school etc.)Contacts
table// Models/Contact.cs
public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Account> Accounts { get; set; }
}
// Models/Account.cs
public class Account
{
public int Id { get; set; }
public string Email { get; set; }
public string Description { get; set; }
public int ContactId { get; set; }
public Contact Contact { get; set; }
}
Up
and Down
methods
Up
method describes the changes that will be made with the migration
Email
column from Contacts
table, and creating the new Accounts
tableDown
method describes the changes that will be made if the migration is revertedAccounts
Continue working on CourseAPI.
Lecture
with properties int Id
, DateTime StartTime
, int Length
, Course Course
, and int CourseId
ICollection<Lecture> Lectures
to the Course
modelAddLectures
Scaffold-DbContext "Server=PostgreSQL 12;Host=localhost;Port=5432;Username=postgres;Password=1234;Database=sqlpractice" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models
Create a new ASP.NET Core web app using the API template.
<PackageReference>
lines from the .csproj
file of the previous assignment to this project's .csproj
filesqlpractice
database created in SQL Databases Exercise 1 to the project by using the Database First approach. If you have not yet created the database in PostgreSQL, it can be found hereContinuing the previous exercise,