Reputation: 1550
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.
Upvotes: 0
Views: 3544
Reputation: 19465
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.
Upvotes: 5
Reputation: 100358
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
};
Upvotes: 4
Reputation: 82943
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
};
Upvotes: 0