views:

82

answers:

3

Per the many examples of LINQ I've seen, I'm creating my own data context and tables using code similar to the one below:

class MyDatabase : DataContext {
  public Table<Widget> Widgets;
  public Table<Car> Cars;

  public MyDatabase (string connection) : base(connection) { } 
}

But for every table (Widgets, Cars, etc), I get the warning Field 'TableName' is never assigned. I can't find anyone on Google that also has this problem. I don't feel like I'm doing anything wrong since I'm just copying the LINQ examples I've seen from different places. So what's up with this warning? Is it warning me of a real problem? Or am I missing something?

A: 

The warning is valid because you've created a definition for Widgets and Cars but they are not assigned. This should take care of itself as you build out your data context. You will eventually reference them.

Randy Minder
Could you elaborate on this more? I'm already consuming Widgets and Cars by reading from them. I figure they're automagically populated by the LINQ framework. So when would this warning ever go away?
Mark Canlas
I just checked my code. I've also written my own data context object. Here is how I have each coded (sorry, I cannot get the formatting correct) /// <summary>Represents the Master.Enterprise table in the underlying database.</summary>public Table<FirstSolar.Mes.Core.L2SBusinessEntities.Master.Enterprise> Enterprise{get { return GetTable<FirstSolar.Mes.Core.L2SBusinessEntities.Master.Enterprise>(); } }
Randy Minder
@Randy : you could edit your answer and make it easier for us all to read.
Hogan
A: 

You can solve this problem by assigning them null after declaration.

Comment response - This does not have to be on the same line as the declaration -- just anywhere after the declaration and before it is used. Same line is common tho and is often used for initializers, which is what is needed and why the compiler is complaining.

Hogan
You mean on the same line as the declaration? Resharper says that's redundant.
Mark Canlas
It is redundant. They are null by default.
Randy Minder
Well I guess you have to pick between a compiler warning and a Resharper warning then or (as Randy says) wait till you finish the class and they are not stubs anymore.
Hogan
+1  A: 

Yes, they are spurious.*

In this other question about how DataContext works, we learn that the constructor for DataContext uses reflection to populate the fields at runtime. So Visual Studio is giving you a warning based on the knowledge it has at compile time. It does not know that ultimately these fields are populated before they are consumed.

*Answer based off of someone else's comment found on SO. Might even be wrong!

Mark Canlas
It isn't wrong, and yes: the warning are incorrect: indeed, the compiler cannot detect reflection.
Marc Gravell
A mystery solved by Mark and Marc, way to go guys.
Hogan