21

Pretty simple question. I have a model that has a property which is a System.Uri type. Uris don't have a default parameterless constructor, and no ID field. Is there any way to override my model generation to store it in the DB in a custom way (e.g. just as a string)? In NHibernate, I've done this before by implementing IUserType, but I could not find yet a similar mechanism in CodeFirst.

Obviously, I could create a custom type that uses a Uri under the hood and exposes regular mappable properties & constructor, I'm just curious if there's any way to map this system type so that I don't have to make a wrapper like that.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Paul
  • 35,689
  • 11
  • 93
  • 122

4 Answers4

34

This is a very old question but I just had the same question today. With Entity Framework Core 2.1, you can set up a Value Conversion:

public class MyEntityDbConfiguration : IEntityTypeConfiguration<MyEntity>
{
    public void Configure(EntityTypeBuilder<MyEntity> builder)
    {
        builder.Property(e => e.UriField)
                .HasConversion(v => v.ToString(), v => new Uri(v));
    }
}

public class MyDbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new MyEntityDbConfiguration());
    }
}
dstj
  • 4,800
  • 2
  • 39
  • 61
9

EF does not support custom type mappings like NH.

For System.Uri in particular, I'd use a wrapper property and map the actual value as a string; it's not that bad.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
6

Unfortunately, there is no direct way to map System.Uri to string with EF.

You could however use Data Annotations and attribute your URL property as follows:

[DataType(DataType.Url)]
public string Link { get; set; }

This will able to tell some services that this should be displayed and validated as a URL (ASP.NET and Silverlight for instance have built in support for it).

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
-1

Try doing this..

[Column(Name="MyUri", TypeName="string")]
public Uri MyUri

Make sure you add reference needed for Column Attribute

using System.ComponentModel.DataAnnotations;

Hope that helps...