很简单的问题。我有一个模型,它有一个 System.Uri
类型的属性。 Uri
没有默认的无参数构造函数,也没有 ID 字段。有没有什么方法可以覆盖我的模型生成以自定义方式将其存储在数据库中(例如,作为 string
)?在 NHibernate 中,我之前通过实现 IUserType
来完成此操作,但我在 CodeFirst 中找不到类似的机制。
显然,我可以创建一个自定义类型,它在后台使用 Uri
并公开常规的可映射属性和构造函数,我只是想知道是否有任何方法可以映射此系统类型,以便我不必制作那样的包装器。
最佳答案
这是一个非常古老的问题,但我今天刚遇到同样的问题。使用 Entity Framework Core 2.1,您可以设置 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());
}
}
关于c# - 使用 Entity Framework Fluent Api 映射 System.Uri,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5037022/