Microsoft.EntityFrameworkCore Namespace
Namespace: Microsoft.EntityFrameworkCore
Assembly: Microsoft.EntityFrameworkCore.dll
Provides core types and abstractions for Entity Framework Core, a modern object-relational mapper (ORM) for .NET.
Summary
The Microsoft.EntityFrameworkCore
namespace contains the fundamental classes and interfaces that power Entity Framework Core (EF Core). This includes DbContext, DbSet, query features, change tracking, and the core configuration mechanisms.
Key Classes and Interfaces
DbContext
Represents a session with the database and can be used to query and save data.
Represents a session with the database.DbSet<TEntity>
Represents a set of entities of a particular type in the context, or that can be queried from the database.
Represents a set of entities.EF
Provides access to EF Core specific operations and methods that do not fit on LINQ's IQueryable
.
IModel
Represents the metadata model of the context.
Represents the model metadata.DbContextOptions<TContext>
Options for configuring a DbContext
instance.
ChangeTracker
Gets a `ChangeTracker` that is aware of entities in the current context.
Tracks changes to entities.Common Operations
1. Defining Your Model
You typically define your entity classes and then use them to create a derived DbContext
class.
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public ICollection<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; }
}
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;Trusted_Connection=True;");
}
}
2. Querying Data
Use LINQ to query data from your DbSet
properties.
using var db = new BloggingContext();
// Retrieve all blogs
var blogs = db.Blogs.ToList();
// Retrieve a blog by its URL
var firstBlog = db.Blogs.FirstOrDefault(b => b.Url.Contains("example.com"));
3. Saving Data
Add, modify, or remove entities and then call SaveChanges
.
using var db = new BloggingContext();
// Add a new blog
var newBlog = new Blog { Url = "http://newblog.com" };
db.Blogs.Add(newBlog);
db.SaveChanges();
// Update an existing blog
var blogToUpdate = db.Blogs.Find(1);
if (blogToUpdate != null)
{
blogToUpdate.Url = "http://updatedblog.com";
db.SaveChanges();
}
// Remove a blog
var blogToRemove = db.Blogs.Find(2);
if (blogToRemove != null)
{
db.Blogs.Remove(blogToRemove);
db.SaveChanges();
}