Dynamic table names in Linq to SQL

Hello everyone I have a terrible database that I need to work with, and linq to sql is the im option, which is used to retrieve data. anyone trying to reuse a function by throwing another table name based on user choice, and there is no reason to change TEntity or Table <> in a DataContext query.

This is my current code.

public void GetRecordsByTableName(string table_name){

string sql = "Select * from " + table_name;
var records = dataContext.ExecuteQuery</*Suppossed Table Name*/>(sql);

ViewData["recordsByTableName"] = records.ToList();
}

I want to populate my ViewData with Enumerable entries.

+3
source share
2 answers

You can call the ExecuteQuery method on the DataContext instance. You want to call an overload that accepts an instance of the type described here:

http://msdn.microsoft.com/en-us/library/bb534292.aspx

, , , Type SQL , .

+3

casperOne, ExecuteQuery (, Type). , , :

public IEnumerable<YourType> RetrieveData(string tableName, string name)
        {
            string sql = string.Format("Select * FROM {0} where Name = '{1}'", tableName, name);

            var result = YourDataContext.ExecuteQuery(typeof(YourType), sql);

            return result;
        }

YourType, ( ). , SQL. , ExecuteQuery "" . :

//This is a hypothetical table mapped from LINQ DBML

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ClientData")]
    public partial class ClientData : INotifyPropertyChanging, INotifyPropertyChanged
    {
private int _ID;

        private string _NAME;

        private string _AGE;
}

//This would be your custom type that emulates your ClientData table

public class ClientDataCustomType 
    {

        private int _ID;

        private string _NAME;

        private string _AGE;
}

, ExecuteQuery :

var result = YourDataContext.ExecuteQuery(typeof(ClientDataCustomType), sql);
0

Source: https://habr.com/ru/post/1703145/


All Articles