views:

117

answers:

1

This is an in-depth continuation of my question from earlier this morning, which I'm still stumped about. I'm using a strongly typed DataContext for my application and although it emits a warning, it magically works. How does it do this?

Here's the code one would typically use to connect to a database using LINQ-to-SQL.

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

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

Even though it emits a warning, it works out of the box. One can begin reading from it using:

using (var db = new MyDatabase(connectionString)) {
  foreach (var w in db.Widgets)
    Console.WriteLine(w);
}

Widgets seems to be a field of the MyDatabase class. And in my code, I'm not assigning it to anything. But elsewhere, I'm reading from it and it has values. Why?

In other examples of LINQ-to-SQL, including code generated by Visual Studio 2008's DBML layout tool, the data context class may look like this:

public partial class MyDatabase : DataContext {
  public Table<Widget> Widgets {
    get {
      return GetTable<Widget>();
    }
  }
}

Notice the inclusion of partial and GetTable. Is the partial necessary?

I'm assuming my first example works by ultimately calling GetTable, but then where is this code coming from? How are the fields of my data context class being populated with data?

+1  A: 

If they are not properties, the only logical conclusion is that the base constructor has assigned them. Unexpected, perhaps, but not impossible.

The partial allows you to combine multiple code files into a single class; you only need it if you have separated your code file (usually for designers).

Some digging in reflector shows that the ctor calls into private void InitTables(object schema), which does exactly this (reflecting over the fields, assigning them via GetTable(Type)).

Marc Gravell
Muy bueno! So, to answer my question from this morning, is it spurious? In as much as the compiler can't sense the reflection in the constructor, right?
Mark Canlas
@Mark - right. The warnings are incorrect: the compiler cannot detect reflection.
Marc Gravell