3

I have some code in a C# program I am working on that builds a list of tables using LINQ:

List<string> tables = 
(from tb in db.Tables.Cast<Table>()
where this.FilterTables(tb, this.Options)
select string.Format("[{0}].[{1}]", tb.Schema, tb.Name)).ToList(); 

I was hoping to easily add a flag that to the list that indicates whether the table has a primary key defined (we don't want tables without primary keys to be excluded but the program needs to process them differently). We came up with the following as what we hoped might work but no such luck. Note, in the code below, "HASPRIMARYKEY" is just a placeholder that I made up to illustrate what we are trying to do -- I was hoping that there would be something like this already but I can't seem to find it.

List<Tuple<string,bool>> tables = 
(from tb in db.Tables.Cast<Table>()
where this.FilterTables(tb, this.Options)
select new Tuple<string, bool>
  (string.Format("[{0}].[{1}]", tb.Schema, tb.Name), 
  tb.HASPRIMARYKEY)).ToList();

I have found solutions (in StackOverflow and elsewhere) that show how to determine the name of the Primary Key column but that isn't what we need. I also have the SQL query that would return the flag to me but we would like to just add it to the existing LINQ query.

Can anyone please tell me if there is an easy way to do this?

Thank you in advance!

  • What kind of data access technology are you using? What is the type of the db variable? – Yacoub Massad Sep 04 '15 at 21:28
  • [This may be similar](http://stackoverflow.com/questions/735140/c-sharp-linq-to-sql-refactoring-this-generic-getbyid-method/735888#735888) - Check the OP's question, it's been updated with a solution. – TestWell Sep 04 '15 at 21:51
  • The db variable is a Microsoft.SqlServer.Management.Smo.Database object. –  Sep 05 '15 at 05:32
  • Create a view of the SQL query and map it to your context. – Gert Arnold Sep 05 '15 at 21:41
  • Can you have your tables classes inherit from an abstract class? Are your primary keys marked with a filter `[Key]`? – Travis J Sep 18 '15 at 20:24

0 Answers0