Skip to content

Instantly share code, notes, and snippets.

@jsheridanwells
Last active May 1, 2018 20:41
Show Gist options
  • Save jsheridanwells/5eaf57ac6f307953ec01f0f78b300e8d to your computer and use it in GitHub Desktop.
Save jsheridanwells/5eaf57ac6f307953ec01f0f78b300e8d to your computer and use it in GitHub Desktop.

EF Core Tutorial Notes

(From this tutorial)...

Make sure you have these workloads:

  • DotNet Desktop Development
  • Data Storage and Processing
  • ASP and Web Development * .Net Core Cross Platform Development

To update DB on solutions:

  • Open NuGet console
  • enter $ Update-Database

To check if you have SqlLocalDB, open developer command prompt and: sqllocaldb, should bring up version sqllocaldb info will show databse instances sqllocaldb info <INSTANCE> will show inof on specfic database In VS, use SQL Server Object Explorer to see DBs Right click -> Properties -> connection String

  • this will show data source: -> Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
  • In this case Data Source=(localdb)\MSSQLLocalDB

Install EF

Create new project -> Templates -> Visual C# -> .NetCore -> console App

Install EF via NuGet Console: PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer Install tools: PM> Install-Package Microsoft.EntityFrameworkCore.Tools

create an Entity

Create Entities directory Add class (Actor.cs) and create properties:

   class Actor
   {
       public int Id { get; set; }
       public string Name { get; set; }
       public int Age { get; set; }
       public bool AcademyWinner { get; set; }
   }

Create a DB Context

DbSet ->> The is an entity, each DbSet maps to a Db Table

Create Entities\ActorDbContext.cs

Inherit from DbContext (pull in using EFCore) Add DbContext property

   class ActorDbContext : DbContext
   {
       public DbSet<Actor> Actors { get; set; }
   }

Override the Databse builder:

       protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
       {
           optionsBuilder.UseSqlServer(
                   @"Server=(localdb)\mssqllocaldb;Database=ActorDb;"
                   + "Trusted_Connection=True;"
               );
       }

(In a real application, the connect string would be in an appsettings file, read out through configuration manager)

Migrations

In NuGet Console: PM> Add-Migration InitialMigration, this will scaffold the Db Schema (will not create Db yet)

To run the migration: Update-Database

you casn see the migrtion in the Sql Server Object Explorer, and you can manually add data with View Data

Seed the Database

In Program.cs, add:

           using (var db = new ActorDbContext())
           {
               db.Actors.AddRange(
                       new Actor
                       {
                           Name = "Ewan McGregor",
                           Age = 45,
                           AcademyWinner = false
                       },
                       new Actor
                       {
                           Name = "Kelly MacDonals",
                           Age = 41,
                           AcademyWinner = false
                       },
                       new Actor
                       {
                           Name = "Ewan Bremmer",
                           Age = 47,
                           AcademyWinner = false
                       },
                       new Actor
                       {
                           Name = "Johnny Lee Miller",
                           Age = 44,
                           AcademyWinner = false
                       }
                   );
               db.SaveChanges();
           }

Quick run of the app, in the same using block:

               var count = db.SaveChanges();

               Console.WriteLine($"{ count } records were added");
               foreach (var actor in db.Actors)
               {
                   Console.WriteLine($"Name: { actor.Name }");
                   Console.WriteLine($"Age: { actor.Age }");
                   if (actor.AcademyWinner)
                   {
                       Console.WriteLine("Academy award winner");
                   }
                   else
                   {
                       Console.WriteLine("Not an academy award winner");
                   }

               }

               Console.ReadLine();

Part 2...

Creating an MVC App w/ DB-First Approach

New MVC App, Install-Package EF Core also install:

PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer
PM> Install-Package Microsoft.EntityFrameworkCore.Tools
PM> Install-Package Microsoft.EntityFrameworkCore.Design
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

(if you ever get nuget errors: PM> dotnet nuget locals all --clear)

this command will create Entity Classes from an existing database:

PM> Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=ActorDb;Trusted_Connection=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Registering Context With Dependency Injection

Remove OnConfiguring method (this will go in Startup)

Create constructor in ActorDbContext:

public ActorDbContext(DbContextOptions<ActorDbContext> options) : base(options)
        { }

In Startup:ConfigureServices add:

            var connection = @"Server=(localdb)\mssqllocaldb;Database=ActorDb;Trusted_Connection=true;";

            services.AddDbContext<ActorDbContext>(opt => opt.UseSqlServer(connection));

Creating Controllers

Create Controllers\ActorsController.cs:

    public class ActorsController : Controller
    {
        private readonly ActorDbContext _context;
        public ActorsController(ActorDbContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View(_context.Actors.ToList());
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Actors actors)
        {
            if (ModelState.IsValid)
            {
                _context.Add(actors);
                _context.SaveChanges();
                return RedirectToAction(nameof(Index));
            }
            return View(actors);
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment