Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
372 views
Welcome To Ask or Share your Answers For Others

1 Answer

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());
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...