No suitable constructor found for entity type 'Uri'.

Viewed 3148

I have this model:

public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Uri Link { get; set; }
}

I added it to fluent-api using the following code:

 builder.Entity<Book>(entity => {
     entity.HasKey(b => b.Id);
 });

when I run this:

add-migration InitialMigration -context MyAppContext

then I get:

No suitable constructor found for entity type 'Uri'. The following parameters could not be bound to properties of the entity: 'uriString', 'uriString', 'dontEscape', 'baseUri', 'relativeUri', 'dontEscape', 'uriString', 'uriKind', 'baseUri', 'relativeUri', 'serializationInfo', 'streamingContext', 'baseUri', 'relativeUri', 'flags', 'uriParser', 'uri'.

2 Answers

You can't persist a Uri directly to the database, as there's no associated SQL type for that. You need to use a string instead. If you're using a view model (as you should be), your view model can have the Uri, and then you simply need to get the string representation during your mapping to your actual entity type.

You can also simply utilize EF Core's value conversion (available in 2.1+). See the docs for more detail. Essentially, in your fluent config:

.HasConversion(
    v => v.ToString(),
    v => new Uri(v));

A value conversion can be added to your DbContext to convert the type used when reading from or writing to the database. This is done by overriding the OnModelCreating method.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<Book>()
        .Property(e => e.Link)
        .HasConversion(v => v.ToString(), v => new Uri(v));
}
Related