[英]How to Convert 'Uri' into String when using entity framework core
I want to create database tables using Entity framework core from POCO-classes. 我想使用POCO类中的Entity Framework Core创建数据库表。 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'" 当我尝试添加新的脚手架项目(选项:在VS中使用Entity Framework(CRUD)的Razor页面)时,出现错误消息:“找不到适合于实体类型'Uri'的构造函数”
Ive learnt that (amongst others) Uri has to be converted into String in the OnModelCreating method (in the class which inherits from dbContext). 我已经了解到,(除其他外)Uri必须在OnModelCreating方法中(在从dbContext继承的类中)转换为String。
DbContext class: dbContext类:
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. 我知道在输入命令“ Add-Migration Initial”时会调用OnModelCreating方法。 But since I tried to auto-implement the CRUD classes, I cannot enter the command "Add Migration Initial". 但是由于我尝试自动实现CRUD类,因此无法输入命令“ 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 . 其中创建代表Uri路径的字符串。
if you need to convert the Uri
to string use Uri property Uri.AbsolutePath
this will return you the string conversion of Uri
. 如果需要将Uri
转换为字符串,请使用Uri属性Uri.AbsolutePath
返回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. 我终于找到了解决我问题的方法:尽管我确实编写了一个从DbContext继承的SchoolDbContext类,但是我没有指定该特定类作为我的数据库访问的Context。 When creating a new scaffold item (Razor pages using Entity Framework (CRUD)), you are asked to specify the model class and the context class. 当创建一个新的脚手架项目(使用实体框架(CRUD)的剃刀页面)时,要求您指定模型类和上下文类。 Instead of generating a new context (which I did all the time) using the '+'-button, I had to specify my SchoolDbContext class. 不必使用“ +”按钮生成新的上下文(我一直都这样做),而是必须指定SchoolDbContext类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.