在LINQ-to-SQL中将URI映射到字符串字段 [英] Mapping a URI to String-field in LINQ-to-SQL
本文介绍了在LINQ-to-SQL中将URI映射到字符串字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用LINQ将URI作为字符串存储在数据库中.
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
我需要怎么做才能正确处理代码中的URI,但是将其存储为数据库中的nvarchar(255)?看起来很简单,但我不知道自己在哪里做错了.
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.
推荐答案
和往常一样,写下问题可以帮助我意识到问题所在.以下代码解决了我的问题:
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;
这篇关于在LINQ-to-SQL中将URI映射到字符串字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文