Best way of constructing dynamic sql queries in C#/.NET3.5?

后端 未结 12 2829
走了就别回头了
走了就别回头了 2021-02-15 11:25

A project I\'m working on at the moment involves refactoring a C# Com Object which serves as a database access layer to some Sql 2005 databases.

The author of the existe

12条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-15 11:52

    I'm coming at this late and have no chance for an upvote, but there's a great solution that I haven't seen considered: A combination of procedure/function with linq-to-object. Or to-xml or to-datatable I suppose.

    I've been this in this exact situation, with a massive dynamically built query that was kindof an impressive achievement, but the complexity of which made for an upkeep nightmare. I had so many green comments to help the poor sap who had to come along later and understand it. I was in classic asp so I had few alternatives.

    What I have done since is a combination of function/procedure and linq. Often the total complexity is less than the complexity of trying to do it one place. Pass some of the your criteria to the UDF, which becomes much more manageable. This gives you a manageable and understandable result-set. Apply your remaining distinctions using linq.

    You can use the advantages of both:

    • Reduce the total records as much as possible on the server; get as many crazy joins taken care of on the server. Databases are good at this stuff.
    • Linq (to object etc.) isn't as powerful but is great at expressing complex criteria; so use it for various possible distinctions that add complexity to the code but that the db wouldn't be much better at handling. Operating on a reduced, normalized result set, linq can express complixity without much performance penalty.

    How to decide which criteria to handle in the db and which with linq? Use your judgement. If you can efficiently handle complex db queries, you can handle this. Part art, part science.

提交回复
热议问题