What's the difference between creating a Context with DbContext and DataContext?

3

What's the difference between creating a Context with DbContext and DataContext? Is there any performance difference or best practice between one or the other?

See the examples below;

namespace _DBContext.DBase.Banco
{
    public class dbContext : using System.Data.Entity.DbContext
    {
        public dbContext()
            : base("EntityConn")
        {
            Database.SetInitializer<dbContext>(null);
        }

        public DbSet<Tabela_DocsIten> Tabela_DocsIten { get; set; }
    }
}
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="MeuBD")]
public partial class ModeloColDataContext : System.Data.Linq.DataContext
{
    public System.Data.Linq.Table<Tabela_DocsIten> Tabela_DocsItens
    {
        get
        {
            return this.GetTable<Tabela_DocsIten>();
        }
    }
}
    
asked by anonymous 03.11.2016 / 17:32

2 answers

2

DbContext represents a combination of the standards Unit-Of-Work and Repository and allows you to query a database and group the changes that will be written back to the storage as a unit. DbContext is conceptually similar to ObjectContext .

Commonly used with a derived type that contains DbSet<TEntity> , these sets are automatically initialized when the derived class instance is created. This behavior can be modified by applying the SuppressDbSetInitializationAttribute attribute to any derived context class or individual properties in the class.


DataContext represents the main entry point for the LINQ to SQL framework. DataContext is the source of all mapped entities in a database connection. It tracks changes made to all retrieved entities and maintains an "identity cache" ensures that entities retrieved more than once are represented by using the same object instance.

In general, a DataContext instance is designed to last for a "unit of work" however, the application defines that term. DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances in the method scope or as a member of the short classes representing a logical set of database operations.


References:

04.11.2016 / 13:04
2

The DbContext is one class and represents a combination of the Work Unit and Repository patterns and can be used to perform queries in the Database.

The DataContext is one class and represents the entry point for the realization of LINQ to SQL.

We can use both, but since you are using EF you should use DbContext. In practice the complete auto is much more simplified (less attributes than the DataContext + its attributes of the domains) using the DbContext compared with the DataContext. Reference

    
04.11.2016 / 03:14