问题
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