查询不显示另一个表是否具有空值(序列不包含任何元素)

时间:2014-03-02 20:38:17

标签: mysql asp.net linq asp.net-mvc-3

我遇到以下代码问题。如果所有表都至少有一个值,则显示详细信息,但如果至少有一个表没有值,则显示任何内容。我收到了消息

  

序列不包含任何元素。

我的代码如下:

public sneakerDetails GetSneakerDetails(int id)
{
    IQueryable<sneakerDetails> query = from sneaks in _context.sneakers
                                       from image in _context.sneakerImages 
                                       from website in _context.sneakerWebsites 
                                       // from website in _context.sneakerWebsites 
                                       where sneaks.sneaker_id == id && image.sneaker_id == website.sneaker_id && sneaks.sneaker_id == website.sneake_id
                                       select new sneakerDetails
                                       {
                                           //sneaker_id = sneaks.sneaker_id,
                                           Colorway = sneaks.Colorway,
                                           Name = sneaks.Name,
                                           description = sneaks.description,
                                           imageAlternative = image.imageAlternative,
                                           release_date = sneaks.release_date,
                                           imageB = image.imageB,
                                           imageF = image.imageF,
                                           imageL = image.imageL,
                                           imageR = image.imageR,
                                           website = website.website,
                                           websiteLogo = website.websiteLogo
                                       };


    return query.ToList().First();

我尝试将返回值更改为FirstOrDefault但是当我点击特定的运动鞋时,它只显示标题而没有数据。

我是否需要为两个表编写if语句?

1 个答案:

答案 0 :(得分:0)

尝试DefaultIfEmpty()

from sneaks in _context.sneakers.DefaultIfEmpty()
from image in _context.sneakerImages.DefaultIfEmpty()
from website in _context.sneakerWebsites.DefaultIfEmpty()
// from website in _context.sneakerWebsites 
where sneaks.sneaker_id == id
    && image.sneaker_id == website.sneaker_id
    && sneaks.sneaker_id == website.sneake_id
select new sneakerDetails
{
    //sneaker_id = sneaks.sneaker_id,
    Colorway = sneaks.Colorway,
    Name = sneaks.Name,
    description = sneaks.description,
    imageAlternative = image.imageAlternative,
    release_date = sneaks.release_date,
    imageB = image.imageB,
    imageF = image.imageF,
    imageL = image.imageL,
    imageR = image.imageR,
    website = website.website,
    websiteLogo = website.websiteLogo
};