Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I modify this linq query to return some empty fields instead of just omitting the data that doesn't fit the join?

Tags:

c#

linq-to-sql

public IQueryable<RecentlyCreatedAssetViewModel> getRecentlyCreatedAssetsByCompanyID(int companyID)
        {
            return (from a in db.Assets 
                    join ab in db.AssetBundles on a.AssetID equals ab.AssetID 
                    join b in db.Bundles on ab.BundleID equals b.BundleID
                    where a.CompanyID == companyID && a.AssetTypeID == 11 && a.IsActive == true && a.ShowInResults == true
                    orderby a.CreateDate descending 
                    select new RecentlyCreatedAssetViewModel { AssetID = a.AssetID, AssetName = a.AssetName, AssetTypeID = a.AssetTypeID, BundleIcon = b.BundleIcon, BundleName = b.BundleName }).Take(10);
        }

It turns out that I want to also get back some db.Assets that do not have relations in db.AssetBundles, however I am not sure how to do this, I want to put empty space (blank strings) in the place of the Bundle fields of the RecentlyCreatedAssetViewModel when there is no relation. This query will not return an Asset that has no relation in the joins though, how can I change this so that it will give them back just putting empty strings in the missing data?

like image 471
MetaGuru Avatar asked Dec 11 '25 04:12

MetaGuru


2 Answers

Here's an article about doing LEFT JOINs in Linq-to-sql; Essentially what you are looking for is the DefaultIfEmpty() extension.

like image 156
Chris Shaffer Avatar answered Dec 12 '25 18:12

Chris Shaffer


Use a LEFT JOIN in your query to get the job done.

More information can be found at W3Schools.

like image 32
Marty McVry Avatar answered Dec 12 '25 18:12

Marty McVry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!