简体   繁体   中英

How to Convert 'Uri' into String when using entity framework core

I want to create database tables using Entity framework core from POCO-classes. When I try and add a new scaffold item (option: Razor pages using Entity Framework (CRUD) in VS), there's an error saying: "No suitable constructor found for entity type 'Uri'"

Ive learnt that (amongst others) Uri has to be converted into String in the OnModelCreating method (in the class which inherits from dbContext).

DbContext class:

    public class SchoolDbContext : DbContext {
      public DbSet<Student> Students { get; set; }

      protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity<Student>()
        .Property(t => t.Homepage)
        .HasConversion(
        v => v.ToString(),
        v => new Uri(v));
      }
    }

Student class:

    public class Student {
      public int ID { get; set; }
      public Uri Homepage {get; set; }
    }

I know that the OnModelCreating method is called when the command "Add-Migration Initial" is entered. But since I tried to auto-implement the CRUD classes, I cannot enter the command "Add Migration Initial". Thanks a lot and excuse my poor english..

var uri = new Uri(path);
uri.AbsolutePath();

If I understand correctly what you are asking , You can try writing :

Path.Combine(Homepage.Segments);

Which create string that represent the path of the Uri .

if you need to convert the Uri to string use Uri property Uri.AbsolutePath this will return you the string conversion of Uri . eg:

  public class Student
   {
       public int ID { get; set; }
       public Uri Homepage { get; set; }
   }
   Student s= new Student();
   string myUri = s.Homepage.AbsolutePath;
or

    public class SchoolDbContext : DbContext {
    public DbSet<Student> Students { get; set; }

          protected override void OnModelCreating(ModelBuilder modelBuilder) {
            modelBuilder.Entity<Student>()
            .Property(t => t.Homepage.AbsolutePath);
          }
        }

Ive finally found a solution to my problem: Though I did write a SchoolDbContext class which inherited from DbContext, I didnt specify that specific class to be the Context for my Database accesses. When creating a new scaffold item (Razor pages using Entity Framework (CRUD)), you are asked to specify the model class and the context class. Instead of generating a new context (which I did all the time) using the '+'-button, I had to specify my SchoolDbContext class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM