Implement LINQ to SQL/Entity like behavior in custom object
I'm curious how exactly the Enity Framework integrates with LINQ in order to generate SQL statements to run agai开发者_运维百科nst the database.
So lets say I have my own custom collection object. How do you integrate that object with LINQ to generate SQL statements?
If you wanted to make your own collection that created SQL statements, then what you would do is to have your collection class implement the IQueryable
interface. As part of this interface, when the Linq expression is executed, the .NET framework will pass a Linq Expression Tree to your custom implementation of IQueryable. Your code would then parse this expression tree, and generate the SQL as needed, or do whatever other actions are needed, and return the result.
Edit: Adding Links
- Walkthrough: Creating an IQueryable Linq Provider (MSDN)
- Using IQueryable with Linq
- Building an IQueryable provider series (The Wayward Weblog)
You have to implement certains interfaces (IQueryable for example) over your custom class in order to use Linq to query over them. Also, if you have a collection composing your class, then you can expose its Enumerator in order to gain in this terrain (Implement IEnumerable). See: How to implement IQueryable
If you need a much specialized "Linq" functionality, like the one that is used in Linq to SQL to translate a Linq expression to T-SQL, then Linq is like a standard: Diferent set of technologies implement Linq diferently, but with certain guidelines. That is correct for Linq to XML, Linq to Entities, Linq to SQL, etc. See:
Walkthrough: Creating an IQueryable LINQ Provider
To help anyone out there with similar requirements, I've written a series of tutorials on how to create a simple LINQ provider, parse expression trees, convert them into the desired output (e.g. SQL) and compile. Having developed one such provider for a production system, I eventually thought the experience might help someone else, with the challenge being to find the time to put it into writing. I've greatly benefited in the past from others sharing their knowledge, especially on subjects where it is scarce, so, hopefully, this may also find an audience:
- How to write a LINQ to SQL provider in C# Part 1 - Introduction
- How to write a LINQ to SQL provider in C# Part 2 - Expression Visitor
- How to write a LINQ to SQL provider in C# Part 3 - Where Clause Visitor
- How to write a LINQ to SQL provider in C# Part 4 - Compiling Expression Trees
精彩评论