MVCEntityFrameworkCore.md - brainchildservices/curriculum GitHub Wiki
Entity Framework (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology.
EF Core can serve as an object-relational mapper (O/RM), which:
- Enables .NET developers to work with a database using .NET objects.
- Eliminates the need for most of the data-access code that typically needs to be written.
EF Core supports many database engines, see Database Providers for details.
With EF Core, data access is performed using a model. A model is made up of entity classes and a context object that represents a session with the database. The context object allows querying and saving data. For more information, see Creating a Model. .
EF supports the following model development approaches:
- Generate a model from an existing database.
- Hand code a model to match the database.
- Once a model is created, use EF Migrations to create a database from the model. Migrations allow evolving the database as the model changes.
using System.Collections.Generic; using Microsoft.EntityFrameworkCore;
namespace Intro
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=Blogging;Integrated Security=True");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public int Rating { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
Instances of your entity classes are retrieved from the database using Language Integrated Query (LINQ). For more information, see Querying Data.
using (var db = new BloggingContext())
{
var blogs = db.Blogs
.Where(b => b.Rating > 3)
.OrderBy(b => b.Url)
.ToList();
}
using (var db = new BloggingContext())
{
var blog = new Blog { Url = "http://sample.com" };
db.Blogs.Add(blog);
db.SaveChanges();
}
While EF Core is good at abstracting many programming details, there are some best practices applicable to any O/RM that help to avoid common pitfalls in production apps:
- Intermediate-level knowledge or higher of the underlying database server is essential to architect, debug, profile, and migrate data in high performance production apps. For example, knowledge of primary and foreign keys, constraints, indexes, normalization, DML and DDL statements, data types, profiling, etc.
- Functional and integration testing: It's important to replicate the production environment as closely as possible to:
- Find issues in the app that only show up when using a specific versions or edition of the database server.
- Catch breaking changes when upgrading EF Core and other dependencies. For example, adding or upgrading frameworks like ASP.NET Core, OData, or AutoMapper. These dependencies can affect EF Core in unexpected ways.
- Performance and stress testing with representative loads. The naïve usage of some features doesn't scale well. For example, multiple collections Includes, heavy use of lazy loading, conditional queries on non-indexed columns, massive updates and inserts with store-generated values, lack of concurrency handling, large models, inadequate cache policy.
- Security review: For example, handling of connection strings and other secrets, database permissions for non-deployment operation, input validation for raw SQL, encryption for sensitive data.
- Make sure logging and diagnostics are sufficient and usable. For example, appropriate logging configuration, query tags, and Application Insights.
- Error recovery. Prepare contingencies for common failure scenarios such as version rollback, fallback servers, scale-out and load balancing, DoS mitigation, and data backups.
- Application deployment and migration. Plan out how migrations are going to be applied during deployment; doing it at application start can suffer from concurrency issues and requires higher permissions than necessary for normal operation. Use staging to facilitate recovery from fatal errors during migration. For more information, see Applying Migrations.
- Detailed examination and testing of generated migrations. Migrations should be thoroughly tested before being applied to production data. The shape of the schema and the column types cannot be easily changed once the tables contain production data. For example, on SQL Server, nvarchar(max) and decimal(18, 2) are rarely the best types for columns mapped to string and decimal properties, but those are the defaults that EF uses because it doesn't have knowledge of your specific scenario.
In this tutorial, you create a .NET Core console app that performs data access against a SQLite database using Entity Framework Core.
You can follow the tutorial by using Visual Studio on Windows, or by using the .NET Core CLI on Windows, macOS, or Linux.
Install the following software:
.NET Core CLI |
---|
.NET Core SDK |
Visual Studio |
---|
Visual Studio 2019 version 16.3 or later with this workload: |
.NET Core cross-platform development (under Other Toolsets) |
Create a new project
dotnet new console -o EFGetStarted
cd EFGetStarted
.NET Core CLI |
---|
dotnet add package Microsoft.EntityFrameworkCore.Sqlite |
Visual Studio |
---|
Tools > NuGet Package Manager > Package Manager Console |
Run the following commands: |
Install-Package Microsoft.EntityFrameworkCore.Sqlite |
Tip: You can also install packages by right-clicking on the project and selecting Manage NuGet Packages
Create the model
In the project directory, create Model.cs with the following code
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace EFGetStarted
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
// The following configures EF to create a Sqlite database file as `C:\blogging.db`.
// For Mac or Linux, change this to `/tmp/blogging.db` or any other absolute path.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite(@"Data Source=C:\blogging.db");
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; } = new List<Post>();
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}
EF Core can also reverse engineer a model from an existing database.
Tip: This application intentionally keeps things simple for clarity. Connection strings should not be stored in the code for production applications. You may also want to split each C# class into its own file.
The following steps use migrations to create a database.
.NET Core CLI
-
Run the following commands:
* dotnet tool install --global dotnet-ef * dotnet add package Microsoft.EntityFrameworkCore.Design * dotnet ef migrations add InitialCreate * dotnet ef database update
In Visual Studio
-
Run the following commands in Package Manager Console (PMC)
* Install-Package Microsoft.EntityFrameworkCore.Tools * Add-Migration InitialCreate * Update-Database
This installs the PMC tools for EF Core. The Add-Migration command scaffolds a migration to create the initial set of tables for the model. The Update-Database command creates the database and applies the new migration to it.
Open Program.cs and replace the contents with the following code:
using System;
using System.Linq;
namespace EFGetStarted
{
internal class Program
{
private static void Main()
{
using (var db = new BloggingContext())
{
// Note: This sample requires the database to be created before running.
// Create
Console.WriteLine("Inserting a new blog");
db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
db.SaveChanges();
// Read
Console.WriteLine("Querying for a blog");
var blog = db.Blogs
.OrderBy(b => b.BlogId)
.First();
// Update
Console.WriteLine("Updating the blog and adding a post");
blog.Url = "https://devblogs.microsoft.com/dotnet";
blog.Posts.Add(
new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" });
db.SaveChanges();
// Delete
Console.WriteLine("Delete the blog");
db.Remove(blog);
db.SaveChanges();
}
}
}
}
Run the app
.NET Core CLI
* dotnet run
in Visual Studio
* Debug > Start Without Debugging
- Create A simple Webapp to implement Entityframework.Core
- Create a database StudentDB
- it should contain 2 tables,
StudentDetails
&Grades
- Grades Containing:- GradeID, Grade.
- StudentDetails Containing:- StudentID, Name, Department, Age & Grade..
add migration using entity framework core