The default Entity framework conventions can be overridden through two methods
1.Data Annotations
2.Fluent API.
Entities and properties are configured through EntityTypeConfiguration. The ModelBuilder class provides Enity (),which return EntityTypeConfiguration object which is  used in configuration.  We can separate out the configurations into a separate class wherein all configurations are consolidated at one place. This class must inherit from the EntityTypeConfiguration.
In the context class’s constructor add this configuration instance to the DbSets’s configuration property.
Public  class MyConfiguration: EntityTypeConfiguration
{
Public MyConfiguration(){
this.HasRequired(s=>s.Name);
this.property(d=>d.address).HasColumnName(“Location”);
}
}

Now in the Context class, add the following lines
Public  class RetailContext: DbContext
{
public RetialContext()
{
this.Configuration.Add( new MyConfiguration());
//this.Configuration.LazyLoadingEnabled = false;
//this.Configuration.ProxyCreationEnabled = false;
//Here we can also enable or disable lazyloading ad proxy Creation.
}
}

In order to create a custom initialization strategy we have to inherit from the default initialization strategy.
Public  MyDbInitialization: DropCreateDatabaseAlways<>
{
protected override void seed( FullContextClass obj)
{
obj.Customer.AddorUpdate(x=>x.Id, new Customer(){
Id=35,Name=”Shami”,items= new Hashset
{
new Item(){ ItemCode=”12SE”,
ItemName=”Lily Deo”,
price=345}
}
});

To use this initialization strategy call
Database.setInitializer(new MyDbInitialization());
either in context costructor or in any class where you wish to initalize the Database.

Happy Learning and Coding.

Advertisements