Entity Framework Core Migrations and CRUD

VerifiedCaution

Skill for Entity Framework Core operations: adding fields, generating migrations, creating new entities, and CRUD operations in the Zagreb Events project.

Sby Skills Guide Bot
DevelopmentIntermediate
7/22/2026
Claude CodeCursorCodex
#entity-framework#dotnet#database-migrations#csharp#sql-server

Recommended for

Automated summary

Step-by-step playbook for Entity Framework Core work in the Zagreb Events project: adding entity properties, creating tables, and generating/applying EF migrations.

Strengths

  • Supplies exact `dotnet ef migrations add` / `database update` commands with `--startup-project` and `--context` already filled in
  • Encodes the project's annotation conventions (key, FK, `virtual` navigation, decimal(10,2), `[NotMapped]`)
  • Also covers `HasData()` seeding and common pitfalls (cascade delete cycles, N+1 queries, EnsureCreated)
  • States clear prohibitions: don't hand-edit `Migrations/`, don't set `Id` manually on insert

Limitations

  • Tightly bound to the Zagreb Events layout (`lab3/` folders, `ZagrebEvents` database, SQLEXPRESS) and not reusable as-is elsewhere
  • Assumes a Windows/PowerShell environment with `dotnet ef` already installed
  • Does not address production migrations, rollbacks, or merge conflicts between migrations
When to use it

Use it whenever a data-model change, a new entity, or an EF Core migration is requested in the Zagreb Events project.

When not to use it

Avoid it for a different .NET project, a non-SQL-Server database, or work unrelated to EF such as pure Razor/controller edits.

Security analysis

Caution
Quality score88/100

The skill is a legitimate Entity Framework Core guide and does not contain exfiltration, obfuscation, or destructive system commands. However, it does instruct the agent to run migration and database update commands, which can modify or damage the local database if used carelessly, so it warrants caution rather than a fully safe rating.

Findings
  • •Instructs running `dotnet ef database update`, which applies schema changes to a local SQL Server database and can cause data loss if migrations are destructive.
  • •No explicit dev/prod guardrail is stated, though the connection string targets `localhost\SQLEXPRESS` with Windows auth.
How this analysis is made

Examples

Add field to Event
Dodaj novo polje Žanr (Genre) u model Event kao string max 50 znakova i generiraj migraciju.
New entity + migration
Kreiraj novu tablicu Tag s Id i Name, dodaj DbSet u ZagrebEventsDbContext i napravi migraciju te update baze.
Seed data
Dodaj seed podatke za Tag (Underground, Mainstream) preko HasData u OnModelCreating.

name: Entity Framework Skill description: Koristi se kad trebamo dodati izmjenu u EF model klasu, generirati novu migraciju ili dodati novi entitet u DbContext. Aktivira se na zahtjeve poput "dodaj novo polje u Event", "kreiraj novu tablicu", "dodaj migraciju".

Entity Framework Skill — Zagreb Events

Pomaže pri svakoj radnji vezanoj uz Entity Framework Core u Zagreb Events projektu.

Projekt struktura

lab3/
├── ZagrebEvents.Model/      ← Klase entiteta (Event, Venue, User...)
├── ZagrebEvents.DAL/        ← ZagrebEventsDbContext + Migrations/
└── ZagrebEvents.Web/        ← Controlleri, viewovi, appsettings.json

Connection string

Definiran u lab3/ZagrebEvents.Web/appsettings.json pod ključem ZagrebEventsDbContext. Server: localhost\SQLEXPRESS, baza: ZagrebEvents, Windows auth.

Kad se dodaje novo polje u postojeći model

  1. Dodaj property u model klasu (npr. lab3/ZagrebEvents.Model/Event.cs):

    [MaxLength(50)]
    public string? Genre { get; set; }
    
  2. Pravila za anotacije:

    • Primarni ključ: [Key] public int Id
    • Strani ključ: [ForeignKey(nameof(Venue))] public int VenueId
    • Navigacija: public virtual Venue? Venue (s virtual za lazy loading)
    • 1-N kolekcija: public virtual ICollection<Event> Events
    • Decimal za novac: [Column(TypeName = "decimal(10,2)")]
    • Computed property: [NotMapped] da EF ne pokuša mapirati u DB
  3. Generiraj migraciju iz developer terminala:

    cd lab3/ZagrebEvents.DAL
    dotnet ef migrations add NazivIzmjene --startup-project ../ZagrebEvents.Web --context ZagrebEventsDbContext
    
  4. Primijeni migraciju na bazu:

    dotnet ef database update --startup-project ../ZagrebEvents.Web --context ZagrebEventsDbContext
    

Kad se dodaje nova tablica/entitet

  1. Kreiraj novu klasu u ZagrebEvents.Model/:

    using System.ComponentModel.DataAnnotations;
    
    namespace ZagrebEvents.Model
    {
        public class Tag
        {
            [Key]
            public int Id { get; set; }
    
            [Required, MaxLength(50)]
            public string Name { get; set; } = "";
    
            public virtual ICollection<Event> Events { get; set; } = new List<Event>();
        }
    }
    
  2. Dodaj DbSet<T> u ZagrebEventsDbContext.cs:

    public DbSet<Tag> Tags { get; set; } = null!;
    
  3. Ako postoji veza, konfiguriraj je u OnModelCreating() ili kroz anotacije.

  4. Generiraj migraciju i update.

Seed podaci

Dodaju se u OnModelCreating() pomoću HasData():

modelBuilder.Entity<Tag>().HasData(
    new Tag { Id = 1, Name = "Underground" },
    new Tag { Id = 2, Name = "Mainstream" }
);

Važno: pri seedanju navigation properties se NE postavljaju, samo FK ID-jevi.

CRUD operacije u controllerima

// READ jedan
var ev = _db.Events
    .Include(e => e.Venue)
    .Include(e => e.Reviews).ThenInclude(r => r.User)
    .FirstOrDefault(e => e.Id == id);

// READ više
var list = _db.Events.Where(e => e.IsUpcoming).ToList();

// CREATE
_db.Events.Add(newEvent);
_db.SaveChanges();

// UPDATE
var ev = _db.Events.Find(id);
ev.Name = "Novi naziv";
_db.SaveChanges();

// DELETE
_db.Events.Remove(ev);
_db.SaveChanges();

Česte greške

  • Cascade delete cycle: kad više FK-jeva ima cascade, EF baca grešku. Riješiti s OnDelete(DeleteBehavior.Restrict) u OnModelCreating.
  • N+1 queries: koristi Include() i ThenInclude() za eager loading.
  • Migracija ne radi: provjeri jel --startup-project točno postavljen i da Web projekt ima Microsoft.EntityFrameworkCore.Design paket.

Što agent NE smije

  • Ne smije ručno mijenjati datoteke u Migrations/ folderu (to je auto-generirano).
  • Ne smije postavljati Id ručno pri INSERT-u (ostavi EF da generira).
  • Ne smije koristiti _db.Database.EnsureCreated() umjesto migracija.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/entity-framework-core-migrations-and-crud-mrwak8i9/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/entity-framework-core-migrations-and-crud-mrwak8i9' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/entity-framework-core-migrations-and-crud-mrwak8i9/download' --output '.skill-downloads/entity-framework-core-migrations-and-crud-mrwak8i9/SKILL.md.part' && mv '.skill-downloads/entity-framework-core-migrations-and-crud-mrwak8i9/SKILL.md.part' '.skill-downloads/entity-framework-core-migrations-and-crud-mrwak8i9/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

This file does not provide a usable name/description header for this native procedure. It remains available to download and inspect; use the manual method below.

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/entity-framework-core-migrations-and-crud-mrwak8i9/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills