0

I'm trying to use Code First and LINQ to read all rows from a table "players".

I already had this working, but then I moved some classes between namespaces (because I was told too) and it's suddenly not working anymore.

It shows a NullReferenceException on "var result = query"

Here's my code

public static List<Player> GetPlayers()
    {
        using (ScoresContext context = new ScoresContext())
        {
            var results = from s in context.players
                          orderby s.name ascending
                          select s;
            List<Player> resultList = new List<Player>();
            foreach (var item in results)
            {
                resultList.Add(new Player(item.Id, item.name, item.nickname));
            }
            return resultList;
        }
    }

[DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class ScoresContext : DbContext
    {
        public DbSet<Game> games { get; set; }
        public DbSet<Player> players { get; set; }
        public DbSet<Score> scores { get; set; }
    }

My connectionString hasnt changed since it worked so that isn't the problem I think.

public class Player
{
    [Key]
    public int Id { get; set; }
    public string name { get; set; }
    public string nickname { get; set; }
    public virtual ICollection<Score> scores { get; set; }

    public Player()
    {

    }

    public Player(int ID, string name, string nickname)
    {
        this.Id = ID;
        this.name = name;
        this.nickname = nickname; 
    }
}

any advice is welcome, let me know if I forgot something so I can add it

Exception information:

System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=MySql.Data.Entity.EF6
  StackTrace:
       at MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
       at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
       at MySql.Data.Entity.MySqlManifestTokenResolver.ResolveManifestToken(DbConnection connection)
       at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
       at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
       at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
       at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
       at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
       at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
       at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
       at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
       at System.Linq.Queryable.OrderBy[TSource,TKey](IQueryable`1 source, Expression`1 keySelector)
       at Logic.Handling.GetPlayers() in C:\Users\Jonathan\Source\Repos\1617_CSProgTech_VanDyckJonathan\labo03\Logic\Handling.cs:line 51
       at labo03.MainForm.refresh() in C:\Users\Jonathan\Source\Repos\1617_CSProgTech_VanDyckJonathan\labo03\labo03\Form1.cs:line 54
       at labo03.MainForm..ctor() in C:\Users\Jonathan\Source\Repos\1617_CSProgTech_VanDyckJonathan\labo03\labo03\Form1.cs:line 19
       at labo03.Program.Main() in C:\Users\Jonathan\Source\Repos\1617_CSProgTech_VanDyckJonathan\labo03\labo03\Program.cs:line 23
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
  • Where do you get the exception exactly? Here: `foreach (var item in results)` or here: `resultList.Add(new Player(item.Id, item.name, item.nickname));`? Anyway, use the debugger and you will find out the reason. – Tim Schmelter Apr 26 '17 at 13:54
  • I bet it's the fact that `results` is not a `List<>` and you are using it in `foreach (var item in results)`. Change it to `foreach (var item in results.ToList())` – Jason Krs Apr 26 '17 at 13:56
  • @JasonKrs That doesn't make any sense. If `ToList()` can enumerate `results` in a `foreach` and put it all in a `List`, why can't OP enumerate it in a `foreach` as well? – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 13:56
  • I don't see why debugging is helping me, I already know the "var results" is null, I just don't know why, my DbContext is not null. It seems something is going wrong during the connection, but don't know how I would troubleshoot this – Jonathan Van Dyck Apr 26 '17 at 14:00
  • @JasonKrs that is not the case, the code doesn't even reach that part now and it worked fine before, I tried it to be sure but it makes no difference – Jonathan Van Dyck Apr 26 '17 at 14:02
  • @JonathanVanDyck Now you're changing your story. In your question, you claimed that you were getting an exception in the LINQ, but now you're claiming that the LINQ is returning null. That's not true, though. `results` isn't `null`. Put in a breakpoint and find out what *is* `null`. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:02
  • @JonathanVanDyck Ok in that case : did you make sure data exist in the database for `players` – Jason Krs Apr 26 '17 at 14:03
  • Is `context` null? Is `context.players` null? Is `s` ever null when order by looks at `s.name`? – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:03
  • @EdPlunkett when I make a breakpoint and hover over "results" it says null, this is a pastebin of the exception details, if that's any help https://pastebin.com/YLjZnGkF – Jonathan Van Dyck Apr 26 '17 at 14:05
  • Nobody here will ever click on a pastebin link, but you can paste the stack trace text into your question. Select the whole stacktrace text and press Ctrl+K to indent it, so it'll be relatively readable. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:06
  • @JasonKrs yes, the database has entries for all 3 tables, I even put those in using the same application before it stopped working, I can check the contents with SQLWorkbench so I'm sure they are there – Jonathan Van Dyck Apr 26 '17 at 14:07
  • 1
    You'll see `null` for `results` before the debugger executes the LINQ. That doesn't mean the LINQ returned null, because the LINQ hasn't executed yet. It means that the debugger knows that reference is about to be initialized. *Assigning* to a null reference doesn't throw an exception (we'd all be in a heck of a pickle if it did, when you think about it). Trying to access members of a null reference throws an exception. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:08
  • I tried putting the stacktrace in a ctr+K block but it's not formatting properly... sorry in advance, it's gonna be ugly – Jonathan Van Dyck Apr 26 '17 at 14:11
  • @JonathanVanDyck Ugly's fine, I can reformat it if I need to. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:13
  • It won't even allow me to post it, says i need to indent with 4 spaces or use ctr+k, but I am using ctr+K! what? – Jonathan Van Dyck Apr 26 '17 at 14:16
  • OK, I wantonly violated my own most deeply held moral convictions and clicked on a pastebin link. The exception is being thrown in `MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection connection)`. It's a problem with your DB connection, maybe a configuration thing. [You're not the first one to get a null reference exception in that method.](https://www.google.com/search?q=nullreferenceexception+in+MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection+connection)) – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:20
  • Let this be a lesson: You've got one downvote (not mine), three close votes, and some guy peddling a novel conspiracy theory about how `foreach` is implemented, but if you'd included the top method from the stack trace it would've all gone very differently. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:25
  • thank you for breaking your moral code for me dear sir, by "configuration thing", do you mean something wrong in my app.config? or could it be somewhere else too? also how can I add : base() to my Context class if there is already a : DbContext? PS: I tried to add my stack trace, it wouldn't let me, hardly my fault? – Jonathan Van Dyck Apr 26 '17 at 14:26
  • Haven't a clue about `DbContext`, I never touch the stuff. I *think* it might be in your app.config or whatever -- but click on that google search link I gave you a couple comments back, there's a lot of hits that look promising to me. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:28
  • Allright I'll give it all a good read, ty sir, and to everyone thats marking this as an "exact duplicate", go mess yourself, I checked the problem thats supposed to be exactly the same, its a massive post with 2 lines about LINQ that are completely unrelated – Jonathan Van Dyck Apr 26 '17 at 14:30
  • Another avenue would be to identify exactly what you changed that broke it. A third would be to just recreate the entity framework stuff. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:31
  • 1
    @EdPlunkett HAHAHAHAHA Ed...I was trying to help. I'm not a conspirationist lol – Jason Krs Apr 26 '17 at 14:34
  • @JonathanVanDyck Dont get irritated. Welcome on Stackoverflow. RESEARCH before posting – Jason Krs Apr 26 '17 at 14:37
  • What they mean about it being a duplicate is that we get a lot of really lazy null reference questions, and people get jaded and start jumping to conclusions. Yeah, you should have provided more info -- but you're new here and comments exist so we can ask for it. It may be a duplicate of one of the questions in those google results, but it's not a lazy null reference question. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:40
  • I double, triple and quadruple checked my app.config file to make sure my connectionstring is in order, it is. I really don't know what else could be messing up my db connection – Jonathan Van Dyck Apr 26 '17 at 14:41
  • If you got it working originally, just recreate it and see what's different. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 14:42
  • All I did was move my classes to a Logic namespace so it's not in the same namespace as my GUI anymore, the needed references and using statements are in place. Could it be because it was first using one app.config file and now another? they are basicly identical now, except for the startup lines in the GUI namespace – Jonathan Van Dyck Apr 26 '17 at 14:46
  • "All I did was..." -- the most famous last words in programming. Second prize goes to "basically identical". Something obviously changed. Quit spinning your wheels and recreate the EF thing. – 15ee8f99-57ff-4f92-890c-b56153 Apr 26 '17 at 15:01
  • 1
    I've given up, I have all the code I need so I'm going to start from scratch, something messed up moving the classes around. Ty for your time anyways, much appreciated – Jonathan Van Dyck Apr 26 '17 at 15:11

0 Answers0