I wrote a simple .NET Core console application to explore EF Core using the code first approach and I followed the below steps (windows machine).
- Create a new .NET Core console application
dotnet new console -o CodeFirstDemo
- cd into the
CodeFirstDemodirectory
cd CodeFirstDemo
- run the application, which compile and produce the output
dotnet run
- Now to start Entity Framework Core, add the EF Core package for SQL Server
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
- Open the
CodeFirstDemodirectory in VS code
code .
- Add a new file called
Posts.csto the project via VS code
using System;
using System.Collections.Generic;
using System.Linq;
namespace CodeFirstDemo
{
public class Post
{
public int PostId {get; set;}
public DateTime DatePublished {get; set;}
public string Description {get; set;}
public string Body {get; set;}
}
}
- Add another file called
BlogDBContext.csvia VS code
using System;
using Microsoft.EntityFrameworkCore;
using System.Configuration;
namespace CodeFirstDemo
{
public class BlogDBContext : DbContext
{
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=CodeFirstDemo;Trusted_Connection=True;");
}
}
- Update the
Program.csfile as shown below
using System;
namespace CodeFirstDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Creating dbcontext...");
BlogDBContext dbContext = new BlogDBContext();
Console.WriteLine("Creating post entry...");
Post post = new Post()
{
// do not insert PostId because it is marked as Identity column
DatePublished = DateTime.Now,
Description = "Description.",
Body = "Body."
};
Console.WriteLine("Adding post to posts dbset...");
dbContext.Posts.Add(post);
Console.WriteLine("Saving to database!");
dbContext.SaveChanges();
// wait for input to keep the console open
Console.ReadLine();
}
}
}
- Now run the program
dotnet run
- The program fails with this
SqlException(0x80131904):
Creating dbcontext...
Creating post entry...
Adding post to posts dbset...
Saving to database!
Unhandled exception. Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open database "CodeFirstDemo" requested by the login. The login failed.
How to fix this error?