c# - 使用 Entity Framework Fluent Api 映射 System.Uri

标签 c# entity-framework ef-code-first ef-fluent-api

很简单的问题。我有一个模型,它有一个 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/

相关文章:

entity-framework - Entity Framework Code first - FOREIGN KEY 约束问题

c# - 从 C# LINQ 解析 XML 时如何保留空白字符

c# - 返回一个泄露实现细节的委托(delegate)

c# - 设置上个月及其年份的格式

c# - 如何交换两个子实体值

c# - 什么约定将 poco 属性自动映射到列?我怎样才能禁用该自动映射?

c# - Linq 查询以匹配 xml 中的字符串值

c# - 错误 : "The specified LINQ expression contains references to queries that are associated with different contexts"

asp.net - Usermanager.DbContext 已在中间件中处置

c# - 如何删除 Entity Framework Core 2.0 中的特定迁移?