0

I'm filling my reference to the entity model with data, but then it turns into null and I don't understand why.

public SummaryContent_Main GetContent(int ID1, int ID2, eComponentType ComponentType)
{
    IEnumerable<vw_WebSiteSummaryContent> entity = null;
    Entities context = new Entities ();

    int maxID = context.vw_WebSiteSummaryContent.Max(webSiteSummaryContent => webSiteSummaryContent.ID);

    entity = context.vw_WebSiteSummaryContent
        .Where(c => c.ID > ID2 && c.CourseID == ID1 && 
               (c.UserID == userToken.UserID || c.Shared == true));

    if (entity.Count() > 0) <<< --- FAILS 
    .
    .
    .
}

Exception:

'entity.Count()' threw an exception of type 'System.NullReferenceException' int {System.NullReferenceException}

When looking at "entity" in Watch, it is not null. What can cause this problem?

Craig W.
  • 17,838
  • 6
  • 49
  • 82
Aa Yy
  • 1,702
  • 5
  • 19
  • 34
  • what does Watch tell you that entity is comprised of? – DaniDev Mar 20 '18 at 17:14
  • 1
    The problem come from the query that define the entity. Since the entity is an IEnumerable, the query get executed only when the Count is call. Check if the userTonken is null. – Stephan Mar 20 '18 at 17:16
  • @Stephan Is there another way of executing it? I'm checking if the token is null before that (I didn't post the full method), and i got to know if my entity has rows – Aa Yy Mar 20 '18 at 17:22
  • Change the declaration from IEnumerable to IList. Add the .ToList() at the end of the query and it will be executed immediately – Stephan Mar 20 '18 at 17:25
  • @Stephan Now I get the same exception but on that query, before .Count() – Aa Yy Mar 20 '18 at 17:30
  • @DaniDev Could you be more specific please? I'm not sure that this is what you meant but it got CommandText,Context etc.. – Aa Yy Mar 20 '18 at 17:39
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Igor Mar 20 '18 at 17:43
  • 1
    Something *in* the lambda statement is throwing the NRE. You only observe it when you execute `.Count()` because that is when the lambda is evaluated and executed against the data store. Validate your parameters that you are using in the lambda including any nested values. – Igor Mar 20 '18 at 17:44
  • @Igor when running the query in SQL Server Management, it works – Aa Yy Mar 20 '18 at 17:45
  • Post your Exception Stack Trace. Until you do that we are all just guessing at where in the Lambda the NRE is manifesting. – Igor Mar 20 '18 at 17:46
  • 1
    Is `userToken` null? I'd put my money on that being null & throwing the `NullReferenceException` when Count() executes which is when the lambda actually runs. – p e p Mar 20 '18 at 17:47

1 Answers1

0

The problem was caused by a view table - it had more than 1 primary key

Aa Yy
  • 1,702
  • 5
  • 19
  • 34