I am new to Entity framework.I got an opportunity to work EF6 using code first approach .When through some concepts in google for creating mapping rules for custom columns i found one way OnModelCreating()
Is there any other way other than this so that we can create tables in db from code first approach.
If there is way..which is better in what context?
Yes, there is other way to map your classes and it better option. At least, I thonk so. You can create mapper for your model which inherits generic EntityTypeConfiguration and add this mapper OnModelCreating. This way your code will stay clean and its much more easier to manage mappings if you have a lot of models.
Model class:
public class Person
{
public int Id { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
}
Mapper class:
internal class PersonMap
: EntityTypeConfiguration<Person>
{
public PersonMap()
{
// Primary key
this.HasKey(m => m.Id);
// Properties
this.Property(m => m.FullName)
.HasMaxLength(50);
// Table & column mappings
this.ToTable("TABLE_NAME", "SCHEMA_NAME")
this.Property(m => m.Id).HasColumnName("ID");
this.Property(m => m.FullName).HasColumnName("FULL_NAME");
this.Property(m => m.Age).HasColumnName("AGE");
// Relationship mappings
// Map your naviagion properties here if you have any.
}
}
Then you add mapper at OnModelCreating method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new PersonMap());
base.OnModelCreating(modelBuilder);
}