How to use ICollection property to do a bool checkHow do you give a C# Auto-Property a default value?How do I enumerate an enum in C#?How to use LINQ to select object with minimum or maximum property valueType Checking: typeof, GetType, or is?Public Fields versus Automatic PropertiesHow to Sort a List<T> by a property in the objectValidation failed for one or more entities. See 'EntityValidationErrors' property for more detailsWhy not inherit from List<T>?EF6 Map column of type int to entity property type boolError: the declared type of navigation property is not compatible with the result

Is it possible to have a strip of cold climate in the middle of a planet?

Multiplicative persistence

Why is so much work done on numerical verification of the Riemann Hypothesis?

Lowest total scrabble score

Is a bound state a stationary state?

Pre-mixing cryogenic fuels and using only one fuel tank

How can Trident be so inexpensive? Will it orbit Triton or just do a (slow) flyby?

Problem with TransformedDistribution

Is this toilet slogan correct usage of the English language?

Travelling outside the UK without a passport

GraphicsGrid with a Label for each Column and Row

Why should universal income be universal?

Why did the HMS Bounty go back to a time when whales are already rare?

Why Shazam when there is already Superman?

Should I stop contributing to retirement accounts?

How could a planet have erratic days?

What was this official D&D 3.5e Lovecraft-flavored rulebook?

Create all possible words using a set or letters

Strong empirical falsification of quantum mechanics based on vacuum energy density

Calculating Wattage for Resistor in High Frequency Application?

250 Floor Tower

Is it safe to use olive oil to clean the ear wax?

Store Credit Card Information in Password Manager?

Is the U.S. Code copyrighted by the Government?



How to use ICollection property to do a bool check


How do you give a C# Auto-Property a default value?How do I enumerate an enum in C#?How to use LINQ to select object with minimum or maximum property valueType Checking: typeof, GetType, or is?Public Fields versus Automatic PropertiesHow to Sort a List<T> by a property in the objectValidation failed for one or more entities. See 'EntityValidationErrors' property for more detailsWhy not inherit from List<T>?EF6 Map column of type int to entity property type boolError: the declared type of navigation property is not compatible with the result













1















I have the following entities:



public class Order

public int Id get; set;
public ICollection<LineItem> LineItems get; set;


public class LineItem

public int Id get; set;
public int Qty get; set;



I would like to just check if an order has large items (qty > 50), so I would like to add a property to Order class like so:



public class Order

public int Id get; set;
public ICollection<LineItem> LineItems get; set;

public bool HasLargeItems

get

return LineItems.Any(l => l.Qty > 50);





This however, doesn't work because of lazy-loading. But if I use .Include(o => o.LineItems), it will fetch all the LineItems and then do an in-memory comparison. I would rather have this generate and execute a query against the db and just get me back a boolean value.



Is this possible to do as a property of Order entity, or do I have to write some other external query object which uses DbContext to perform these kinds of checks?










share|improve this question




























    1















    I have the following entities:



    public class Order

    public int Id get; set;
    public ICollection<LineItem> LineItems get; set;


    public class LineItem

    public int Id get; set;
    public int Qty get; set;



    I would like to just check if an order has large items (qty > 50), so I would like to add a property to Order class like so:



    public class Order

    public int Id get; set;
    public ICollection<LineItem> LineItems get; set;

    public bool HasLargeItems

    get

    return LineItems.Any(l => l.Qty > 50);





    This however, doesn't work because of lazy-loading. But if I use .Include(o => o.LineItems), it will fetch all the LineItems and then do an in-memory comparison. I would rather have this generate and execute a query against the db and just get me back a boolean value.



    Is this possible to do as a property of Order entity, or do I have to write some other external query object which uses DbContext to perform these kinds of checks?










    share|improve this question


























      1












      1








      1


      0






      I have the following entities:



      public class Order

      public int Id get; set;
      public ICollection<LineItem> LineItems get; set;


      public class LineItem

      public int Id get; set;
      public int Qty get; set;



      I would like to just check if an order has large items (qty > 50), so I would like to add a property to Order class like so:



      public class Order

      public int Id get; set;
      public ICollection<LineItem> LineItems get; set;

      public bool HasLargeItems

      get

      return LineItems.Any(l => l.Qty > 50);





      This however, doesn't work because of lazy-loading. But if I use .Include(o => o.LineItems), it will fetch all the LineItems and then do an in-memory comparison. I would rather have this generate and execute a query against the db and just get me back a boolean value.



      Is this possible to do as a property of Order entity, or do I have to write some other external query object which uses DbContext to perform these kinds of checks?










      share|improve this question
















      I have the following entities:



      public class Order

      public int Id get; set;
      public ICollection<LineItem> LineItems get; set;


      public class LineItem

      public int Id get; set;
      public int Qty get; set;



      I would like to just check if an order has large items (qty > 50), so I would like to add a property to Order class like so:



      public class Order

      public int Id get; set;
      public ICollection<LineItem> LineItems get; set;

      public bool HasLargeItems

      get

      return LineItems.Any(l => l.Qty > 50);





      This however, doesn't work because of lazy-loading. But if I use .Include(o => o.LineItems), it will fetch all the LineItems and then do an in-memory comparison. I would rather have this generate and execute a query against the db and just get me back a boolean value.



      Is this possible to do as a property of Order entity, or do I have to write some other external query object which uses DbContext to perform these kinds of checks?







      c# entity-framework entity-framework-6






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 4:59









      Uwe Keim

      27.7k32133215




      27.7k32133215










      asked Mar 8 at 4:57









      RizRiz

      2,467114678




      2,467114678






















          2 Answers
          2






          active

          oldest

          votes


















          0














          One way to do this is using anonymous select



           var order = dbContext.Orders
          .Where(o => o.Id == id)
          .Select(o => new Order = o, HasLargeItems = o.LineItems.Count > 50 )
          .SingleOrDefault();





          share|improve this answer























          • I know how I can do this outside of the class. I am just asking if it's possible to do efficiently as a property of the entity without having access to dbContext.

            – Riz
            Mar 8 at 5:18











          • Maybe not then.

            – tia
            Mar 8 at 5:20


















          0














          Try this it might help:



          public bool HasItems

          getreturn LineItems.AsQueryable().Any(x => false);






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056963%2fhow-to-use-icollection-property-to-do-a-bool-check%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            One way to do this is using anonymous select



             var order = dbContext.Orders
            .Where(o => o.Id == id)
            .Select(o => new Order = o, HasLargeItems = o.LineItems.Count > 50 )
            .SingleOrDefault();





            share|improve this answer























            • I know how I can do this outside of the class. I am just asking if it's possible to do efficiently as a property of the entity without having access to dbContext.

              – Riz
              Mar 8 at 5:18











            • Maybe not then.

              – tia
              Mar 8 at 5:20















            0














            One way to do this is using anonymous select



             var order = dbContext.Orders
            .Where(o => o.Id == id)
            .Select(o => new Order = o, HasLargeItems = o.LineItems.Count > 50 )
            .SingleOrDefault();





            share|improve this answer























            • I know how I can do this outside of the class. I am just asking if it's possible to do efficiently as a property of the entity without having access to dbContext.

              – Riz
              Mar 8 at 5:18











            • Maybe not then.

              – tia
              Mar 8 at 5:20













            0












            0








            0







            One way to do this is using anonymous select



             var order = dbContext.Orders
            .Where(o => o.Id == id)
            .Select(o => new Order = o, HasLargeItems = o.LineItems.Count > 50 )
            .SingleOrDefault();





            share|improve this answer













            One way to do this is using anonymous select



             var order = dbContext.Orders
            .Where(o => o.Id == id)
            .Select(o => new Order = o, HasLargeItems = o.LineItems.Count > 50 )
            .SingleOrDefault();






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 8 at 5:15









            tiatia

            7,98111939




            7,98111939












            • I know how I can do this outside of the class. I am just asking if it's possible to do efficiently as a property of the entity without having access to dbContext.

              – Riz
              Mar 8 at 5:18











            • Maybe not then.

              – tia
              Mar 8 at 5:20

















            • I know how I can do this outside of the class. I am just asking if it's possible to do efficiently as a property of the entity without having access to dbContext.

              – Riz
              Mar 8 at 5:18











            • Maybe not then.

              – tia
              Mar 8 at 5:20
















            I know how I can do this outside of the class. I am just asking if it's possible to do efficiently as a property of the entity without having access to dbContext.

            – Riz
            Mar 8 at 5:18





            I know how I can do this outside of the class. I am just asking if it's possible to do efficiently as a property of the entity without having access to dbContext.

            – Riz
            Mar 8 at 5:18













            Maybe not then.

            – tia
            Mar 8 at 5:20





            Maybe not then.

            – tia
            Mar 8 at 5:20













            0














            Try this it might help:



            public bool HasItems

            getreturn LineItems.AsQueryable().Any(x => false);






            share|improve this answer



























              0














              Try this it might help:



              public bool HasItems

              getreturn LineItems.AsQueryable().Any(x => false);






              share|improve this answer

























                0












                0








                0







                Try this it might help:



                public bool HasItems

                getreturn LineItems.AsQueryable().Any(x => false);






                share|improve this answer













                Try this it might help:



                public bool HasItems

                getreturn LineItems.AsQueryable().Any(x => false);







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 8 at 5:29









                neelesh bodgalneelesh bodgal

                313




                313



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056963%2fhow-to-use-icollection-property-to-do-a-bool-check%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme