Is this a spurious warning when using LINQ to SQL?
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 r开发者_开发问答eal problem? Or am I missing something?
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!
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.
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.
精彩评论