Search code examples
ef-core-2.0

Is there a way to make Entity Framework Core map all Guid properties to nvarchar without annotations?


I have a domain model that makes use of Guids for primary/foreign keys. Is there a way to instruct the ModelBuilder to explicitly create database tables with nvarchar storage for these properties without applying annotations on every existing primary and foreign key in my entity classes?


Solution

  • Use the Microsoft.EntityFrameworkCore.Storage.ValueConversion.GuidToStringConverter value converter.

    var guidToStringConverter = new GuidToStringConverter();
    
    modelBuilder.Entity<YourEntity>()
        .Property(ye => ye.PropertyThatIsAGuid)
        .HasConversion(guidToStringConverter);