Mapping a URI to String-field in LINQ-to-SQL

被刻印的时光 ゝ 提交于 2019-12-08 02:37:44

问题


I'm trying to store a URI as a string in a database, using LINQ.

[Column(Name = "Url", DbType = "nvarchar(255)")]
public Uri Url
{
    get
    {
        return new Uri(_url);
    }
    set
    {
        _url = value.AbsoluteUri;
    }
}

private string _url;

This maps nicely to my database design, however, when trying to fetch data using this code:

int id = 3;
_serie = new DataContext(connString).GetTable<Serie>();
var serie = _serie.FirstOrDefault(s => s.Id == id);

At the last line, I get an exception

System.InvalidCastException: Invalid cast from System.String to System.Uri etc

What do I need to do get correctly handle a URI in my code, but store it is a nvarchar(255) in my database? It seems simple, but I can't figure out where I'm doing it wrong.


回答1:


As always, writing down the question helped me realize the problem. The following code fixed my problem:

public Uri Url
{
    get
    {
        return new Uri(_url);
    }
    set
    {
        _url = value.AbsoluteUri;
    }
}

[Column(Name = "Url", DbType = "nvarchar(255)")]
private string _url;


来源:https://stackoverflow.com/questions/1612010/mapping-a-uri-to-string-field-in-linq-to-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!