Creating Data Context

When working with the code first model of Entity Framework, we need to define our custom context class, which should be derived from the DbContext class. Any class that inherits from the DbContext class is used to perform the database manipulation on the entities. In our case, we will use IdentityDbContext, which is a wrapper on the DbContext class and takes the IdentityUser object. IdentityDbContext is a generic base class, which can be customized with entity types that extend from the IdentityUser types.

Given next is the DataContext class, which contains the DbSet property for each entity. DbSet represents the entity set that is used to create, update, delete, and read records from a particular table to which the entity is mapped. If DbSet is defined for a particular entity, then the table will be created on running the database migration and the relationship and other constraints will be added based on the configuration defined. Entities that are not defined through the DbSet property will not be affected by migration and their corresponding tables will not be generated.

Here is our DataContext class containing a few DbSet properties and derived from IdentityDbContext class:

    public class DataContext : IdentityDbContext<ApplicationUser> 
{
public DataContext()
{
}

protected override void OnConfiguring(
DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer("Data Source=.;
Initial Catalog=TMS;
Integrated Security=False;
User Id={your_db_userid};
Password={your_db_password};");
}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
+
public virtual void Save()
{
base.SaveChanges();
}

#region Entities representing Database Objects
public DbSet<Employee> Employee { get; set; }
public DbSet<Job> Job { get; set; }
public DbSet<JobTask> JobTask { get; set; }
public DbSet<JobWorker> JobWorker { get; set; }
public DbSet<Property> Property { get; set; }
public DbSet<ServiceRequest> ServiceRequest { get; set; }
public DbSet<Status> Status { get; set; }
public DbSet<Tenant> Tenant { get; set; }
#endregion
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.251