Tutorial :linq to sql “Contains”



Question:

if i have a field in my table that i want to verify exists, how do i use the contains method to determine if it exists.

i would have thought the contains method just takes in a string but it seems to take in my whole linq data object


Solution:1

Contains is an extension method for IEnumerable that determines whether a given object is present in the enumerable. That's not what you want here.

I'm guessing that you have a LINQ query like this:

IEnumerable<string> productNames = from p in db.Products select p.ProductName;  

And now you want to verify that the ProductName field actually exists to avoid run-time errors. There is actually no need to check that. Try replacing p.ProductName by a field that doesn't exist. The compiler will complain.

Of course, this assumes that the actual database schema matches the one used to generate the database class with MSLinqToSQLGenerator.


Solution:2

Not sure how to do it with LINQ but you could do:

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE _NAME ='MyTable' and COLUMN _NAME='MyColumn'  

then based on the count returned from the query you will know if the column exists or not.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »