Can I extend the operators that LINQ-to-SQL suppor

2019-07-21 01:21发布

问题:

If I wanted to badly enough, could I add additional LINQ constructs to LINQ-to-SQL (as I would be able to if creating my own LINQ provider)? For instance, many of the built-in LINQ operators (XYZ.Any()) get directly translated to SQL (e.g. IF EXISTS(XYZ)).

If I needed a specialized construct, would I even be able to augment the set, or does this have to be baked into the actual LINQ-to-SQL provider?

How would I go about adding a new operator implementation? Are C# extension methods enough of a hook to do the job?

If the answer is yes, would someone so inclined be able to replace much (all?) of sproc capability via the dynamic SQL generated by LINQ-to-SQL?

回答1:

In theory you could add support for arbitrary expressions to a LINQ provider, but Pavel is correct that LINQ to SQL would not work as a starting point. I would look into SubSonic or NHibernate, which also have LINQ providers under development. Once the provider supports an expression, you would just need to build an equivalent extension method on IQueryable<T> - reflect System.Linq.Queryable for details.

That said, parsing expression trees is definitely not for the faint of heart. Unless you're really interested in AST theory, it would probably be easier to just extend an OSS ORM in a "normal" way.



回答2:

No, LINQ to SQL is not extensible like that. The best you can do is to use stored procedures.