How to create Mapping rules for custom entities in EF6?

entity-framework entity-framework-6

Question

The Entity Framework is new to me. I got an opportunity to work EF6 using code first approach . I discovered a method for defining mapping rules for custom columns after searching for various ideas on Google.OnModelCreating() Is there any alternative except this one that would allow us to establish databases from code first? Whatever is preferable in which situation, if there is a way?

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

Popular Answer

Yes, there is a better option that allows you to map your courses in another method. I certainly think so. You may add this mapper OnModelCreating and construct mapper for your model, which inherits the generic EntityTypeConfiguration. By doing this, your code will remain clean and managing mappings for a large number of models will be considerably simpler.

Typical class:

public class Person
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public int Age { get; set; }
}

Mapper type:

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 a mapper to the method OnModelCreating:

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