What is the best way to store URI in EF/SQL Server?

David Thielen 3,211 Reputation points
2023-03-05T01:41:17.8533333+00:00

Hi all;

I have some properties in an Entity Framework class that are URIs. Is there a way to store them as a URI in the database? Or should I store them as a string?

The underlying DB is SQL Database on Azure.

thanks - dave

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
779 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,103 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2023-03-06T02:45:14.06+00:00

    @David Thielen, Welcome to Microsoft Q&A, you could refer to the Microsoft Learning Value Conversions to do it.

    Here is a code example you could refer to.

     public class Website
        {
            public int Id { get; set; } 
    
            public string? Name { get; set; }
    
            public Uri uri { get; set; }    
        }
    
        public class MyContext:DbContext
        { 
            public DbSet<Website> websites { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer("");
            }
        }
        public class MyEntityDbConfiguration : IEntityTypeConfiguration<Website>
        {
            public void Configure(EntityTypeBuilder<Website> builder)
            {
                builder.Property(e => e.uri)
                        .HasConversion(v => v.ToString(), v => new Uri(v));
            }
        }
    
    

    I add an entity in the main method:

    static void Main(string[] args)
            {
                Uri uri = new Uri("uri path");
                MyContext context=new MyContext();
                context.websites.Add(new Website() { Name = "web1", uri = uri });
                context.SaveChanges();
    
    
            }
    
    

    After checking, the database could store the URI correctly:

    User's image

    Hope my solution could be helpful.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Newest

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.