Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework class type property to snake case

I want to map Location of type RoomLocation to

Floor -> location_floor,
Building -> location_building,
Room -> location_room

Room.cs

public class Room
{
    [Key]
    public Guid Id { get; set; }
    public string Title { get; set; }
    public RoomLocation Location { get; set; }

    public DateTime CreationDate { get; set; }
    public DateTime ModificationDate { get; set; }  
}

public class RoomLocation
{
    public int Floor { get; set; }
    public int Building { get; set; }
    public int Room { get; set; }
}

Database Diagram

Database diagram

Note: in an older project I forgot to add a builder.HasKey and it actually worked I looked at the logs and Entity Framework translated the query to user_ now because I forgot what exactly happened I can't redo the situation.

I'm using Entity Framework with Npgsql with SnakeCaseNamingConvention.

like image 364
Jamal Abo Mokh Avatar asked Sep 13 '25 05:09

Jamal Abo Mokh


1 Answers

It doesn't seem as though anyone has covered this specifically, but the Entity Framework fluent configuration builder does have an option to define custom table and property mappings.

If I had a table in my database called notifications with some properties called notification_title, date_created and date_modified. You could then map your properties in your class as follows...

Your Model

public class Notification
{
   public DateTime DateCreated { get; set; }
   public DateTime DateModified { get; set; }
   public string NotificationTitle { get; set; }
}

The fluent configurations

public class DataContext : DbContext
{
   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
      modelBuilder.Entity<Notification>(entity =>
      {
         entity.ToTable("notifications");
         entity.Property(p => p.NotificationTitle).HasColumnName("notification_title");
         entity.Property(p => p.DateCreated).HasColumnName("date_created");
         entity.Property(p => p.DateModified).HasColumnName("date_modified");
      });
   }
}

I hope this helps someone. ;)

like image 98
Sludgedog Avatar answered Sep 15 '25 19:09

Sludgedog