LINQ query Joins

旧巷老猫 提交于 2019-12-12 04:04:04

问题


When i use the below code to retrieve information, it shows an error..

var mails = from m in entity.mailboxes
            join p in entity.ordinary_user_profile_info on m.from_id equals p.user_id
            select new MailList
            {
                mid = m.m_id,
                mfrom = m.**from_id,** // Error occours here
                mfomname = p.username,
                msubject = m.subject
            };

Error is:

"int? mailbox.from_id "

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

I have declared m_id and from_id as int in DB as well as in MailList class.


回答1:


var mails = from m in entity.mailboxes
            join p in entity.ordinary_user_profile_info on m.from_id equals p.user_id
            select new MailList
            {
                mid = m.m_id,
                mfrom = m.from_id ?? 0,
                mfomname = p.username,
                msubject = m.subject
            };



回答2:


I'm guessing this should fix it.

so int? is a Nullable type, you need to either

(1) Define MailList.mfrom as an int? OR
(2) Convert from int? to int, like below:

var mails = from m in entity.mailboxes
            join p in entity.ordinary_user_profile_info on m.from_id equals p.user_id
            select new MailList
            {
                mid = m.m_id,
                **mfrom = m.from_id.HasValue ? m.from_id.Value : 0**
               //this is saying is, since the int is nullable, 
               //if it has a value, take it, or return 0
                mfomname = p.username,
                msubject = m.subject
            };

Update


After a little more research, seems like @abatishchev solution with the null-coalescing operator is the correct way to go, according to msdn, and like @Konstantin on the comments mentioned Nullable.GetValueOrDefault(T) is also more correct.




回答3:


Try this:

var mails = from m in entity.mailboxes
            join p in entity.ordinary_user_profile_info on m.from_id equals p.user_id
            select new MailList
            {
                mid = m.m_id,
                mfrom = (int)m.from_id,  // Error occours here
                mfomname = p.username,
                msubject = m.subject
            };


来源:https://stackoverflow.com/questions/4813968/linq-query-joins

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