Entity Framework (EF) is an object-relational mapper (ORM) that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.
Entity Framework allows you to create a model by writing code or using boxes and lines in the EF Designer. Both of these approaches can be used to target an existing database or create a new database.
Entity Framework is the main ORM that Microsoft provides for the .NET Framework and Microsoft’s recommended data access technology.
Entity Framework Code-First provides a set of DataAnnotation attributes, which you can apply to your domain classes and properties. DataAnnotation attributes override default Code-First conventions.
Note: DataAnnotations only give you a subset of configuration options. Fluent API provides a full set of configuration options available in Code-First.
There are two general ways of specifying HOW Entity Framework will map POCO classes to database tables, columns, etc.: Data Annotations and Fluent API.
While Data Annotations are a simple to read and understand, they lack of certain features such as specifying the "Cascade on Delete" behavior for an entity. The Fluent API on the other hand is a bit more complex to use, but provides a far more advanced set of features.
If models are correctly related you can easily load related data using EntityFramework. You have three options to chose from: lazy loading, eager loading and explicit loading.
Models used in examples:
public class Company
{
public int Id { get; set; }
public string FullName { get; set; }
public string ShortName { get; set; }
// Navigation properties
public virtual Person Founder { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class Address
{
public int Id { get; set; }
public int CompanyId { get; set; }
public int CountryId { get; set; }
public int CityId { get; set; }
public string Street { get; set; }
// Navigation properties
public virtual Company Company { get; set; }
public virtual Country Country { get; set; }
public virtual City City { get; set; }
}
Entities in Entity Framework can have various states that are listed by the System.Data.Entity.EntityState enumeration. These states are:
Added
Deleted
Detached
Modified
Unchanged
Entity Framework works with POCOs. That means that entities are simple classes that have no properties and methods to manage their own state. Entity state is managed by a context itself, in the ObjectStateManager
.
This topic covers various ways to set entity state.
Tracking behavior controls whether or not Entity Framework will keep information about an entity instance in its change tracker. If an entity is tracked, any changes detected in the entity will be persisted to the database during SaveChanges()
.