Another Salesforce blog!!!

Salesforce, Apex

DBContext & DBSet


DbContext: Is a simplified alternative to ObjectContext and is the primary object for interacting with a database using a specific model.
DbSet: Is a simplified alternative to ObjectSet and is used to perform CRUD operations against a specific type from the model.

DbContext and DbSet is used for the CodeFirst approach. Which enables a very clean and rapid development workflow.

If we want to create a database called ‘NewDatabase’ and two tables in that called “Country” and ‘State’. Then you will end-up writing the model classes

Add a model class and name it as Country.cs.
[cc]
public class Country
{
[Key]
public virtual int country_id {get; set; }

[Required ]
public virtual string country_name { get; set;}
}

[/cc]

 

Similarly add another class and named it as State.cs.

[cc]

public class State
{
[Key]
public virtual int state_id {get; set; }
[Required ]
public virtual string state_name { get; set;}
}
[/cc]

Add another Model class called ‘NewDatabase.cs’

[cc]
public class NewDatabase:DbContext
{
public DbSet Country { get; set; }
public DbSet State { get; set; }
}
[/cc]

You have to do some more steps.
[cc]
1.Run ‘Enable-Migrations’ command from Package Manager Console
Open Configuration file and set AutomaticMigrationsEnabled = true;
2. Then run ‘Update-Database’ command from Package Manager Console
[/cc]

Leave a Reply

Your email address will not be published. Required fields are marked *

*