如果我的联接失败,那么linq查询似乎会全部失败

本文关键字:失败 查询 全部 linq 那么 我的 如果 | 更新日期: 2023-09-27 17:58:41

我有以下代码:

public SiteViewModel SVMGetByID(int siteID)
{
    SiteViewModel siteViewModel = (
        from site in context.Sites
        join address in context.Addresses on site.AddressID equals address.AddressID
        //join city in context.Cities on address.CityID equals city.CityID
        join country in context.Countries on address.CountryID equals country.CountryID // This needs to be a left join I think?
        join state in context.States on address.StateID equals state.StateID // This needs to be a left join I think?
        where site.SiteID == siteID
        select new SiteViewModel
        {
            SiteID = site.SiteID,
            Name = site.Name,
            AddressID = address.AddressID,
            Address1 = address.Address1,
            Address2 = address.Address2,
            City = address.City,
            State = state,
            StateID = state.StateID,
            Country = country,
            CountryID = country.CountryID,
            ZIP = address.ZIP
        }
    ).FirstOrDefault();
    // If address.CityID and address.StateID have a value the siteViewModel is correctly filled,
    // otherwise it is not.
    return siteViewModel;
}

如果在我的数据库中,我的地址表包含address.CityIDaddress.StateID的空条目,则返回空结果。。。实际上,我希望它返回一个结果,无论联接是否失败(左联接?)

这两列勾选了"允许空值"。。。我的地址模型也表示Nullable<int>是联接词应该是其他词吗

如果我的联接失败,那么linq查询似乎会全部失败

您可以为此使用group join。查看此文档。

示例:

var innerGroupJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
select new { CategoryName = category.Name, Products = prodGroup };

您使用into。。。然后从下面执行一个操作,将其连接到原始查询。

       SiteViewModel siteViewModel = (
            from site in context.Sites
            join address in context.Addresses on site.AddressID equals address.AddressID
            join country in context.Countries on address.CountryID equals country.CountryID into joinedCountry
            from country in joinedCountry.DefaultIfEmpty()
            join state in context.States on address.StateID equals state.StateID into joinedState
            from state in joinedState.DefaultIfEmpty()
            where site.SiteID == siteID
            select new SiteViewModel
            {
                SiteID = site.SiteID,
                Name = site.Name,
                AddressID = address.AddressID,
                Address1 = address.Address1,
                Address2 = address.Address2,
                City = address.City,
                //CityID = city.CityID,
                State = state,
                StateID = state.StateID,
                Country = country,
                CountryID = country.CountryID,
                ZIP = address.ZIP
            }
        ).FirstOrDefault();
        return siteViewModel;