I tried to convert this simple sql query to linq to sql query
SELECT * INTO temptable from EFESRDP0
ALTER TABLE temptable DROP COLUMN PASSWORD,SECONDPASS
SELECT * FROM temptable
DROP TABLE temptable
But I couldnt. Anyhelp would be appreciated, thank you.
Since Linq to SQL has no equivalent for the table operations you're trying to perform, the short answer is you can't do that.
From the structure of the query though it looks like the following is happening:
All records from EFESRDP0 are added to a previously non-existent table temptable
A few columns are dropped from temptable
The remaining data is returned as a recordset
The temporary table is dropped
Which is a long-winded way of specifying a list of columns to return from the original table, isn't it? Bad SQL shouldn't be turned into even worse LINQ, it should be fixed.
In query syntax the simple form would be:
var results =
from row in context.EFESRDP0
select new { row.ID, row.Name, row.LastLoginTime /* or whatever */ };
This will result in an SQL query similar to:
SELECT ID, Name, LastLoginTime
FROM EFESRDP0;
Which is a whole lot simpler than the SQL you posted and appears to do basically the same thing without all the table gymnastics.
Since your SQL statements are effectively returning all columns except Password and SECONDPASS, you can do that with a simple Linq like Corey gave creating a new anonymous type. You can also have a type defined with all the columns except those 2 so you could get a typed result. ie: This sample returns only 3 columns from sample Northwind..Customers table:
void Main()
{
DataContext db = new DataContext(#"server=.\SQLexpress;trusted_connection=yes;database=Northwind");
Table<Customer> Customers = db.GetTable<Customer>();
// for LinqPad
//Customers.Dump();
}
[Table(Name = "Customers")]
public class Customer
{
[Column]
public string CustomerID { get; set; }
[Column]
public string ContactName { get; set; }
[Column]
public string CompanyName { get; set; }
}
Related
I am new to LINQ to SQL and I am getting a weird result with my testing program that I don't want.
The program is a very simple WinForms app that shows SQL results in a DataGridView.
Here is my database setup.
Here is the specific column information per table.
And finally here are the results of the table shown through MSMS
Here is the issue that i'm having.
After establishing the connection to the database, I then run the following.
testingDatabase = new DataClasses1DataContext(SharedVariables.TestingConnection);
var query = from Orders in testingDatabase.GetTable<ORDER>()
select Orders;
//select new { Orders.CUST_ID, Orders.ORDER_NUM, Orders.ORDER_DATE };
return query;
It returns this.
I have also tried this code
testingDatabase = new DataClasses1DataContext(SharedVariables.TestingConnection);
var query = from Orders in testingDatabase.ORDERs
select Orders;
//select new { Orders.CUST_ID, Orders.ORDER_NUM, Orders.ORDER_DATE };
return query;
However the results are the same.
Then only way I can get the results i'm looking for is by doing this
testingDatabase = new DataClasses1DataContext(SharedVariables.TestingConnection);
var query = from Orders in testingDatabase.GetTable<ORDER>()
//select Orders;
select new { Orders.CUST_ID, Orders.ORDER_NUM, Orders.ORDER_DATE };
return query;
Then I finally get this.
Can anyone tell me how to do a "select customers" and have it not show the column displaying "LINQ_Testing.CUSTOMER". I suspect it's because it's the foreign key causing that since it makes an EntityRef variable in the CUSTOMER class.
Try adding a virtual object of Customer class in Order class:
public virtual Customer customer { get; set; }
The foreign key relation in Order class (i.e cust_id) will lazy load the Customer object in it automatically.
I have a list of table names in form of strings. I want to loop through the list and use the table name in the LINQ query:
var db = new SomeContext();
// for a single table I can use the LINQ query as
var res = from q in db.Table
where ......
select q;
and it works just fine.
The above approach is hard coding. I need a generic solution for this to loop through multiple tables whose names are stored in a list.
// list of string containing table names
List<stringtableNames = [Get the table list from some source]
// not a problem here
loop through the table names and for each name execute a LINQ query as shown below
foreach(string table in tableNames)
{
var queryRes = from t in table
where <some_condition>
select t;
}
In the above statements "from t in table" above is not valid as "table" is a string. I need actual table object reference to use.
Need help on how do I go about doing that.
You can use the DbContext.Set method:
Set(System.Type.GetType("TableName"))
Above sentence will return a non generic DbSet. So, you will not be able to query with linq as usual. But you can use dynamic linq. ScottGu will explain it better than me.
Please, check this thread for other solutions.
In EF you can execute SQL Code.
In this example i use EF with SQL (String)
var db = new SomeContext();
var list = db.ExecuteStoreQuery<Obj>(Obj.sql);
class Obj
{
public const string sql = #"select [tbl].[field] from [tbl]";
}
select, where, from is one way to define LINQ but You can use it if you have a list of elements (IEnumerable<T> for example), but You have only name of Your table
I think You have to create a regular SQL query
foreach(string table in tableNames)
{
var query =$"select * from {table} where <some_condition>";
var list = db.ExecuteStoreQuery<Obj>(query);
}
In EF You can execute regular query
I am not the best with oracle sql.
I have List<T> on webservice and I need send list to client side of application.
After that I need write distinct list data in table, and join with few other tables.
For example:
I have define:
public class VIEW_COLOR
{
public int COL_NAME_CODE { get; set; }
public int COL_DESC_CODE { get; set; }
}
I get data with
public List<VIEW_COLOR> GetColor()
{
string sql = "select distinct * from VIEW_COLOR";
IEnumerable<VIEW_COLOR"> loc = _connection.Query<VIEW_COLOR>(sql);
return loc.ToList<VIEW_COLOR"=>();
}
Than i use:
[WebMethod]
public List<VIEW_COLOR> GetColor()
{
return dal.GetLColor();
}
I try this part and I get that in list on webservice list.
I have tables:
Table desc_name have code, tab_col_d_name
Table name_desc have code, tab_col_n_desc
Now i need that application when I input this data to client side , and insert in full_table that have columns:
1. tab_col_name_code
2. tab_col_name_desc
3. tab_col_desc_code
4. tab_col_desc_name
Table desc_name have
1. tab_col_d_name
2. tab_col_d_code
Table name_desc have
1. tab_col_n_desc
2. tab_col_n_code
I need to insert in local full_table tab_col_name_code=COL_NAME_CODE and tab_col_name_desc= tab_col_n_name where tab_col_n_code = COLOR_DESC_CODE (from list) and for second two columns same.
I hope I was clearly with this, I am not best with English and was little hard explain what I try to do.
Q: "I dont know how send list from webserver to client side of apps"
A: Call your server webmethod on client side and get the result.
Q: "how write sql witch wold insert in table "where field = value from list"
A: You may create SQL query dynamically or use some ORM layer to insert data through ORM-generated entities.
I need to query a table from database which has 400 rows and 24 columns. I need to query this table so that on each row and then on each column of row I can perform some C# code ( I can use column information to execute some code).
Now at the moment I am querying each row again and again from table using select statement and storing to a custom list and performing custom operations on it.
Is it best and fastest way of doing it ? or should I just query the whole table one time and store somewhere ? not sure where in a dataset and then run throw custom code to do some operation using information in each row ?
You can fetch the table from database once and store it in datatable and then just use linq to select the column something like this
var data = dt.AsEnumerable().Select(s => s.Field<string>("myColumnName")).ToArray<string>();
and If you don't want to use other columns anywhere in your code then you should select only useful column from the database.
You can also select multiple columns of a database using linq. The values will be stored in anonymous type of object.
var mutipleData = from row
in dt.AsEnumerable()
select new
{ Value1 = row["Column1"].ToString(),
Value2 = row["Column2"].ToString()
};
Assuming that each field is 1000 bytes, the total memory to hold your 400 rows would be 9.6MB. Peanuts! Just read the whole table in a DataTable and process it as you wish.
Select all the records from DB table which are f your concern
Copy the select records into DataTable.
Pseudo Code:
--dt is datatable
foreach(datarow dr in dt.rows)
{
--perform operation
string str=dr["columnname"].tostring
}
400 rows isn't a massive amount, however it depends on the data in each column and how often you are likely to run the query. If all you are going to do is run the query and manipulate the output, use a DataReader instead.
If it's only 400 records, I'd fetch them all at once, store them in a class and iterate over each instance.
Something like:
Class
public class MyTableClass(){
string property1 {get; set;}
string property2 {get; set;}
int property3 {get; set;}
// etc.
}
Logic:
ICollection<MyTableClass> lstMyTableClass = (
from m in db.mytableclass
select m
).ToList();
return lstMyTableClass;
And then a loop:
foreach(var myTableInstance in lstMyTableClass){
myTableInstance.DoMyStuff();
}
If the number of records will always be below thoussand, just query all the records and keep it in a List.
Once the data is in the List you can query the List n number of times using LINQ without hitting the database for each request.
I am using VS2005 C# and SQL Server Database 2005.
I am tying to compare values between 2 databases.
I am able to retrieve the variable [StudentName] from tStudent Table via a SELECT WHERE sql statement, as follow:
Now, I have another table named StudentDetails. It has 3 columns, StudentName,Address and ContactNum:
The situation is that I want to grep the result from the first SQL query on tStudent, which returns me a list of Students whose [Status]=DELETED.
And from the list of Students queried , I want to take one Student at a time, and search through my [StudentDetails] table.
If it exist in [StudentDetails], I wan to use a way to store the variable [StudentName] from StudentDetails table and display it in GridView on my webpage.
(open to many solutions here. store in database; display result in GridView; store in array; etc)
May I know what the ways and steps I can take to achieve the result?
Step by step guide and code snippets are very much appreciated, because I am quite weak in C# programming.
you can do like this:
Use Visual Studio to create a DataSet name StudentDS, create table name "Student" in this DataSet, this table will contain 3 table columns: String StudentName; String Address; String ContactNum;
Fill deleted students into this DataSet:
DataSet dset = new StudentDS();
String connectionString = "";// depends on your database system, refer to http://www.connectionstrings.com
using (connection = new OdbcConnection(connectionString))
{
connection.Open();
command.Connection = connection;
command.CommandText = "select StudentName, Address, ContactNum from tStudent WHERE status = 'DELETE'";
OdbcDataAdapter da = new OdbcDataAdapter();
da.SelectCommand = command;
da.Fill(dset, "Student");
}
- After you get this DataSet, you can iterate on its row to do what you want.
if(dset.Tables[0].Rows != null) {
for (int i = 0; i < dset.Tables[0].Rows.Count, i++){
if(!ExistInStudentDetail(dset.Tables[0].Rows[i]["StudentName"]))
{
dset.Tables[0].Rows.remove(i);
i--;
}
}
}
//here, boolean ExistInStudentDetail(String StudentName) is a method, you can create sql for this as same in above.
In your form, add a new DataGridView name "StudentForm",add 1 column for this DataGridView name "StudentName", and set its binding property to "StudentName" (same column name in DataSet), and then set DataSource of this grid.
StudentForm.DataSource = dSet;
HTH.
This is a fairly simple issues but the scope is pretty large. So here goes:
First you should really make sure you have unique columns in the tables you are searching this allows you to modify those individual rows and make sure that you are modifying the correct one. I didn't see any ID columns in the screenshot so I just wanted to cover this.
Second I would create a class for students. In here I would create fields or properties of all the information that I wanted.
class Student
{
public string Name { get; private set; }
public string Address { get; private set; }
public string ContactNum { get; private set; }
}
you can either use a constructor in the above class and fill the properties with that or you can fill in each through your select your choice.
Third I would create a List<Student> students; this will be used as your reference list
List<Student> deletedStudents = SQL Select Statement;
Fourth I would then create another List<Student> detailedStudents;
Finally I would compare the two lists and then do something when a match is found.