简体   繁体   中英

Create custom property mapping for all properties in EF6

Model:

Entity class as the Id is shared between all entities

public abstract class Entity
{
    public int Id { get; set; }
}

And the Student class, which inherits the Entity class

public class Student : Entity
{
    public string LastName { get; set; }

    public string Forenames { get; set; }

    public DateTime EnrolmentDate { get; set; }

    public virtual ICollection<Enrolment> Enrolments { get; set; }
}

Table columns have the naming convention STUDENT_ID, LAST_NAME, FORENAMES etc. All tables will have the ID column of [NAME]_ID

How do I create a custom mapping for all properties in all entity classes? The code referenced here does not work as the .Entities() method does not exist any more.

Override the OnModelCreating method on the context class, and then you can set a custom name for the ID column for each entity like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>().Property(x => x.Id).HasColumnName("STUDENT_ID");
    modelBuilder.Entity<Teacher>().Property(x => x.Id).HasColumnName("TEACHER_ID");
}

You can use the column attribute to have the custom column name mapping:

public class Student
{
  [Column("STUDENT_ID")]
  public int Id { get; set; }

  //...
}

I am unable to mark both answers as correct (which they are), but the idea I was trying to get to was to set all column names automatically map from ColumnName to COLUMN_NAME without having to specify the column name manually for every property.

I found the answer from Loop over entity column mappings to transform column name which works for every column except the ID column, so I just set these manually with the code that Yacoub Massad suggested.

So:

// Make all properties UPPER_CASE
modelBuilder.Properties()
            .Configure(x => x.HasColumnName(Regex.Replace(x.ClrPropertyInfo.Name, "(?<=.)(?=[A-Z])", "_").ToUpper()));

// Set the ID columns to ENTITY_ID
modelBuilder.Entity<Course>()
    .ToTable("COURSE")
    .Property(x => x.Id)
    .HasColumnName("STUDENT_ID");

Setting the [Column("ENTITY_ID")] attribute for every property would be fine if I didn't have that many tables and columns, but as the database grows and there are more and more entity classes added it can be quite repetitive and could be brittle as it's manually named.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM