问题
I am trying to migrate an old project to using LINQ but I have run into a pretty major problem. The problem is we have dynamic tables for search indexing (CM-system with dynamic attributes). The search index has columns for each searchable attribute { attribute_x, attribute_y, ... }. Now the problem is I cannot statically define which columns are available (or even which table to use as we divide search indexes), so I need a way to do this on the fly.
I have tried using Dynamic Expressions, but they still require a type to build the expression from, and I haven't been able to generate a valid type by reflection. (It seems no MemberInfo is generated).
I could also satisfy with just being able to generate an expression for searching ( but I guess this is no easier task ). Something along the lines of
var mySearchIndex= db.GetTable(myTableType); var query = from p in db.Products from idx in mySearchIndex; query = query.Where( "idx." + attributeName + " > 50.0 && idx." + attributeName + "
would be desirable.
Has anyone come across a solution to this problem? I have been looking through blog posts and forums for the past two days in vain.
回答1:
I don't believe that there is a solution to this using LINQ. At least not that I have ever heard or found. LINQ breaks if the table structure changes and you have to recreate the DataModel every time.
If I am incorrect I am anxious to hear about it. :)
回答2:
You may want to try Linq to Dataset:
LINQ to DataSet makes it easier and faster to query over data cached in a DataSet object. Specifically, LINQ to DataSet simplifies querying by enabling developers to write queries from the programming language itself, instead of by using a separate query language.
回答3:
You're working outside of Linq to SQL's design, but I think it could be done if you really need to. Your best bet to explore is probably the XmlMappingSource that you can use in your context's constructor. I had some success with this when it came to handling table renaming on the fly.
In mapping XML, the actual column name on the database is the "Name" attribute of the column element whereas the class property is the "Member". If you change that in the XML it should map the eventual query appropriately.
来源:https://stackoverflow.com/questions/714401/using-linq-to-sql-with-dynamic-tables