简体   繁体   中英

Dynamically select data runtime from entity framework 6.0 throws exception

I would like to selected dynamic data from entity framework as per below.

if I select "Select * from TableName" in queryString it works fine but if I select only selected column/columns it does not work and throws an exception.

Working ok

string queryString =      @"SELECT * FROM context.TableName ";
DbSqlQuery<SampleTable> result = context.SampleTable.SqlQuery(queryString);

Throws Exception

columnList is generated run time from SampleTable which may consists one or more columns.

 string queryString =      @"SELECT " + String.Join(",", columnList) + " FROM context.TableName ";
 DbSqlQuery<SampleTable> result = context.SampleTable.SqlQuery(queryString);

Exception:

The data reader is incompatible with the specified 'context.TableName ... A member of the type, does not have a corresponding column in the data reader with the same name.

As per my understanding EF try to map all columns but above query does not have same number of columns as set in code and so it throws exception.

You can check the below steps :

  • Use the alias names of columns in your columnList (ex: tablename.Id instead of Id).
  • That all the column names in your columnList are mapped in the Entity.
  • Check that the column names in your columnList are same as of the Entity.

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM