简体   繁体   中英

DefaultIfEmpty() + select new MyStronglyTypeObj()

my aim is to return result via left join by linq . The io.IsDefault can be null but insted of this I want to return MyStronglyTypeObj obj with the rest data.

context.Image.Where(i => i.IsActive == true) have 3 rows. one of those have isDefault null because this ImageId - (io => io.ImageId == i.ImageId) dosent exist in ImageObject

var test2 = (from i in context.Image.Where(i => i.IsActive == true)
             from io in ImageObject.Where(io => io.ImageId == i.ImageId).DefaultIfEmpty()
             select new MyStronglyTypeObj() { Alt = i.Alt, Caption = i.Caption, DisplayName = i.DisplayName, Extension = i.Extension, IsDefault = io.IsDefault, Height = i.Height, Width = i.Width, Name = i.Name });
        // return 2 imgs - the 3rd one without isDefault (isDefault = null) wasn't added to collection.
var test = (from i in context.Image.Where(i => i.IsActive == true)
            from io in ImageObject.Where(io => io.ImageId == i.ImageId).DefaultIfEmpty()
            select i); // return 3 imgs

Is something obvious to me that I don't see? - perhaps I totally misunderstood the .DefaultIfEmpty() function

please help

DefaultIfEmpty() only affects empty collections, and causes that collection to return a single element with value default(T) (where T == collection type).

For example, using strings (note default(string) == null ):

在此处输入图片说明

So based on the code you provided:

  • DefaultIfEmpty() is not a factor
  • The only other difference is the select statement, which doesn't really make sense

I'm guessing i is type MyStronglyTypeObj (based on properties matching)? I suspect there's another factor when you're running this code that you're not taking into account.

Try putting a breakpoint on that line, and viewing the results in the debugger.

Also, because LINQ uses deferred execution, this query code doesn't actually "run" until it gets consumed, and depending on when that happens, the source data can change (essentially, easily causing timing bugs if you're changing the source data somewhere else). Even more frustrating, this can cause this bug to disappear when you use a debugger and view the results in that, as it causes the code to execute sooner. You can avoid this by adding a .ToList() at the end of the line to cause the results to be executed immediately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM