Junior
What is Entity Framework?
sobes.tech AI
Answer from AI
Entity Framework (EF) is an object-relational mapper (ORM) for .NET that allows developers to work with databases using .NET objects rather than writing most of the data access code. It translates LINQ queries into SQL and back.
Main components and features:
- DbContext: Represents a session with the database, including DbSets for entities.
- DbSet: Represents a collection of entities of a specific type within the context.
- LINQ to Entities: Allows writing database queries using LINQ syntax.
- Migrations (Code-First Migrations): Manage database schema changes as the data model evolves in code.
- Change Tracking: EF automatically tracks changes made to entities loaded from the database and generates the appropriate SQL commands to save these changes.
Supported development approaches:
- Code-First: Define the data model in C# code and generate the database schema based on it.
- Database-First: Create a .NET model from an existing database.
- Model-First: Create a graphical model in the EF designer and generate both code and database schema. (Less common in EF Core)
Advantages:
- Accelerates development by abstracting from the details of data access implementation.
- Strong typing and compile-time validation.
- Convenient management of the data model and its changes.
Example of using EF Core (Code-First paradigm):
// Data model definition
public class Blog
{
public int BlogId { get; set; }
public string Url { 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; }
}
// Database context definition
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Example configuration for SQLite
optionsBuilder.UseSqlite("Data Source=blogging.db");
}
}
// Usage example in code
// using (var context = new BloggingContext())
// {
// // Adding data
// context.Blogs.Add(new Blog { Url = "http://example.com/blog" });
// context.SaveChanges();
//
// // Querying data
// var blog = context.Blogs
// .OrderBy(b => b.BlogId)
// .First();
// }
EF Core is a cross-platform, lightweight, and extensible version of Entity Framework, recommended for new .NET applications.