How does a strongly typed DataContext work?

This is a deep continuation of my question from this morning , which I am still worried about. I use a strongly typed DataContext for my application, and although it throws a warning, it magically works. How it's done?

Here, the code is usually used 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) { } } 

Despite the fact that he issues a warning, he works out of the box. You can start 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 in the MyDatabase class. And in my code I do not assign anything. But elsewhere I read from there, and he has values. Why?

In other LINQ-to-SQL examples, including code generated by the Visual Studio 2008 DBML build tool, the data context class might look like this:

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

Note the inclusion of partial and GetTable . Is partial required?

I assume my first example works, ultimately calling GetTable , but where does this code come from? How are the fields of my context data class populated with data?

+4
source share
1 answer

If they are not properties, the only logical conclusion is that they were assigned by the base constructor. Unexpectedly, perhaps, but not impossible.

partial allows you to combine several code files into one class; you only need this if you shared your code file (usually for designers).

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

+3
source

Source: https://habr.com/ru/post/1299984/


All Articles