How to create Mapping rules for custom entities in EF6?

entity-framework entity-framework-6

Question

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?

1
0
7/25/2016 8:25:01 AM

Popular Answer

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);
}
1
7/25/2016 8:46:01 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow