(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
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 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; }
}
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)
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
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();