简体   繁体   English

使用Entity Framework Fluent Api映射System.Uri

[英]Map System.Uri using Entity Framework Fluent Api

Pretty simple question. 非常简单的问题。 I have a model that has a property which is a System.Uri type. 我有一个具有System.Uri类型属性的模型。 Uri s don't have a default parameterless constructor, and no ID field. Uri没有默认的无参数构造函数,也没有ID字段。 Is there any way to override my model generation to store it in the DB in a custom way (eg just as a string )? 有没有办法覆盖我的模型生成,以自定义的方式将其存储在数据库中(例如,只是作为一个string )? In NHibernate, I've done this before by implementing IUserType , but I could not find yet a similar mechanism in CodeFirst. 在NHibernate中,我之前通过实现IUserType实现了这IUserType ,但我在CodeFirst中找不到类似的机制。

Obviously, I could create a custom type that uses a Uri under the hood and exposes regular mappable properties & constructor, I'm just curious if there's any way to map this system type so that I don't have to make a wrapper like that. 显然,我可以创建一个使用Uri的自定义类型并公开常规的可映射属性和构造函数,我只是好奇是否有任何方法来映射这个系统类型,这样我就不必像这样做一个包装器。

This is a very old question but I just had the same question today. 这是一个非常古老的问题,但我今天也遇到了同样的问题。 With Entity Framework Core 2.1, you can set up a Value Conversion : 使用Entity Framework Core 2.1,您可以设置值转换

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());
    }
}

EF does not support custom type mappings like NH. EF不支持NH等自定义类型映射。

For System.Uri in particular, I'd use a wrapper property and map the actual value as a string; 特别是对于System.Uri,我使用包装器属性并将实际值映射为字符串; it's not that bad. 没那么糟糕。

Unfortunately, there is no direct way to map System.Uri to string with EF. 不幸的是,没有直接的方法将System.Uri映射到EF的string

You could however use Data Annotations and attribute your URL property as follows: 但是,您可以使用数据注释并将URL属性归属如下:

[DataType(DataType.Url)]
public string Link { get; set; }

This will able to tell some services that this should be displayed and validated as a URL (ASP.NET and Silverlight for instance have built in support for it). 这将告诉一些服务,这应该显示和验证为URL(例如,ASP.NET和Silverlight内置支持它)。

Try doing this.. 试试这个..

[Column(Name="MyUri", TypeName="string")]
public Uri MyUri

Make sure you add reference needed for Column Attribute 确保添加Column Attribute所需的引用

using System.ComponentModel.DataAnnotations;

Hope that helps... 希望有帮助......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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