LINQ-to-SQL 匿名类型与 null 值的问题
我在 LINQ-to-SQL 和匿名类型方面遇到一些问题。
我有 gridview (它不是那么重要,但它是 Telerik 的 RadGrid),它具有以下数据源:
TSEntities db = new TSEntities();
int idFirma = Convert.ToInt16(Request.QueryString["idt"]);
var ticketList = (from t in db.Ticket
where t.idFirma == idFirma
select t).ToList();
gvTicketi.DataSource = from t in ticketList
where t.idFirma == idFirma
orderby t.idTicket, t.RedniBroj, t.DatumPrijave
select new { t.idTicket, t.idFirma, t.idKontakt, t.idManager, t.idNadredeniTicket, TicketNumber = t.idNadredeniTicket + "-" + t.RedniBroj, t.Biljeske, t.DatumDo, t.DatumPrijave, t.OpciPrioritet, t.Opis, t.OpisZatvoren, t.Prioritet, t.Status, t.Tip, t.VrstaPrijave, t.Zatvoren, NazivKontakta = t.Kontakt.Ime + " " + t.Kontakt.Prezime };
当 NazivKontakta 不为空时,一切正常,但当为 null 时,一切都会崩溃,并出现以下错误:“对象引用未设置为实例一个对象的”,它解释了一切,但并不能帮助我解决问题。
我想做的(如果可能的话)是以某种方式检查空值,如果它为空,我想将“NazivKontakta”设置为字符串值“Empty”,如果它不是空值,则将其设置为来自数据库的值。
有解决方案吗?任何帮助将不胜感激!
先感谢您!
I have some problems with LINQ-to-SQL and anonymous types.
I have gridview (it's not that important, but it is Telerik's RadGrid) which has the following datasource:
TSEntities db = new TSEntities();
int idFirma = Convert.ToInt16(Request.QueryString["idt"]);
var ticketList = (from t in db.Ticket
where t.idFirma == idFirma
select t).ToList();
gvTicketi.DataSource = from t in ticketList
where t.idFirma == idFirma
orderby t.idTicket, t.RedniBroj, t.DatumPrijave
select new { t.idTicket, t.idFirma, t.idKontakt, t.idManager, t.idNadredeniTicket, TicketNumber = t.idNadredeniTicket + "-" + t.RedniBroj, t.Biljeske, t.DatumDo, t.DatumPrijave, t.OpciPrioritet, t.Opis, t.OpisZatvoren, t.Prioritet, t.Status, t.Tip, t.VrstaPrijave, t.Zatvoren, NazivKontakta = t.Kontakt.Ime + " " + t.Kontakt.Prezime };
Everything works fine when NazivKontakta isn't null, but when is null everything crashes with the following error: "Object reference not set to an instance of an object" which explains everything, but doesn't help me to work it out.
What I'd like to do (if possible) is to somehow check for the null value and if it is null I'd like to set "NazivKontakta" to string value "Empty" and if it's not null value to set it to the values from the database.
Is there a a solution for this? Any help would be appreciated!
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑这实际上是导致问题的原因:
即不是
NazivKontakta
为空,而是t.Kontakt
为空。毕竟,如果没有任何东西取消引用NazivKontaka
,就不应该有问题。在您的查询中试试这个:
I suspect it's actually this which is causing the problem:
i.e. not
NazivKontakta
being null, butt.Kontakt
being null. After all, if nothing's dereferencingNazivKontaka
, there shouldn't be a problem.Try this in your query:
尝试
Try
我会编写一个简单的 IsNull 函数或使用 IsDBNull 来检查它是否为 null 返回 string.Empty
I would write a simple IsNull function or use IsDBNull to check and if it is null return string.Empty