I'm kinda new to LINQ, so sorry if my question is dumb.
I need to retrieve some values from a database and put them in textBoxes. Just that. Something like the code below, but using LINQ:
EDIT: actually, I want to retrieve more than one field. Like that:
SqlDataReader dr = new functionThatReturnsDataReader();
if (dr.HasRows) {
dr.Read();
txtId = dr["Id"].ToString();
txtName = dr["Name"].ToString();
}
I've found this solution online:
IDbCommand command = dc.GetCommand(query);
command.Connection = dc.Connection;
command.Connection.Open();
IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
However, it seems like I'm trowing away everything that LINQ stands for if I mix it with a standard executeReader. There's no reason in building a data context and query and them execute them like ADO...
How can I achieve the same without using IDbCommand and IDataReader?
I think you need to create a LINQ to SQL class from your database:
http://msdn.microsoft.com/en-us/library/bb384428.aspx
Then you can treat the database table like an object and query it with linq... without the specifics of the query you are trying to run, I cannot construct the linq query for you, but creating the DBML file is the first step.
One thing to think about when comparing a LINQ (or Entity Framework, or other ORM) solution to an ADO.NET solution is that the ORM's are--generally--strongly typed. This means that you need to apply object-oriented principles to them.
If you're dealing with the context, query, and results all in the same function, you can do this:
using(var context = new YourContext())
{
txtId.Text = (from t in context.YourTable
where t.Conditions
select t.Id).FirstOrDefault();
}
If they're not in the same function (and really, they shouldn't be), then something like this would work:
string FunctionThatReturnsId()
{
using(var context = new YourContext())
{
return (from t in context.YourTable
where t.Conditions
select t.Id).FirstOrDefault();
}
}
...
txtId.Text = FunctionThatReturnsId();
If you are using entity Framework then you dont need any query just write id in text box and hit search button it will show you all records in text box of that id.
EntityFramework_mvcEntities db = new EntityFramework_mvcEntities();
int i =Convert.ToInt32( txtsrch.Text);
Employee p = db.Employees.Find(i);
TextBox1.Text = p.Name;
TextBox2.Text = p.Email;
TextBox4.Text = p.Mobile;
db.SaveChanges();
}
var q = from c in context.GetTable<tbl_user>()
where c.user_ID == lbuserid.Text.ToString()
select new
{
c.Username,
c.firstname
};
foreach (var item in q)
{
lbusername.Text = item.Username;
lbfirstname.Text = item.firstname;
}
Related
How to display the unitfunction value from mysql database and my query is below ,i don't know its right or wrong.
Help me out.
string fundev = "select unitfunctioncode from channels where channel_no = " + Channelid;
MySqlCommand getfun = new MySqlCommand(fundev, Connection1);
Console.WriteLine(getfun);
MAKE ENTITY CONTEXT FIRST:
YourEntity db= new YourEntity();
LINQ:
Console.Write(db.channels.Where(x=>x.channel_no == Channelid).Select(y=>y.unitfunctioncode));
This is modal first approach create modal from database and call this linq in controller
I'm not sure about the specifics of MySqlCommand, but I would expect to see an execute on your getfun object.
I would do something like this:
MySqlDataReader rdr = getfun.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
rdr.Close();
This takes into account multiple rows returned. You can omit the while loop if you're sure you will have a single row returned.
How can I use dynamic queries in C# ? From what I've searched its similiar to when we use SqlCommand with parameters to prevent sql injection(example below).
using (SQLiteConnection DB_CONNECTION = new SQLiteConnection(connectionString))
{
DB_CONNECTION.Open();
string sqlquery = "UPDATE table SET Name =#Name, IsComplete=#IsComplete WHERE Key =#Key;";
int rows = 0;
using (SQLiteCommand command = new SQLiteCommand(sqlquery, DB_CONNECTION))
{
SQLiteParameter[] tableA = { new SQLiteParameter("#Key", todo.Key), new SQLiteParameter("#Name", table.Name), new SQLiteParameter("#IsComplete", table.IsComplete) };
command.Parameters.AddRange(tableA);
rows = command.ExecuteNonQuery();
}
DB_CONNECTION.Close();
return (rows);
}
I'm new to c# and i wondering how can I make this work, thanks in advance.
Basically just build up the string sqlQuery based on a set of conditions and ensure that the appropriate parameters have been set. For example, here is some psuedo-C# (not tested for bugs):
//Set to true, so our queries will always include the check for SomeOtherField.
//In reality, use some check in the C# code that you would want to compose your query.
//Here we set some value we want to compare to.
string someValueToCheck = "Some value to compare";
using (SQLiteConnection DB_CONNECTION = new SQLiteConnection(connectionString))
{
DB_CONNECTION.Open();
string sqlquery = "UPDATE MyTable SET Name =#Name, IsComplete=#IsComplete WHERE Key =#Key";
//Replace this with some real condition that you want to use.
if (!string.IsNullOrWhiteSpace(someValueToCheck))
{
sqlquery += " AND SomeOtherField = #OtherFieldValue"
}
int rows = 0;
using (SQLiteCommand command = new SQLiteCommand(sqlquery, DB_CONNECTION))
{
//Use a list here since we can't add to an array - arrays are immutable.
List<SQLiteParameter> tableAList = {
new SQLiteParameter("#Key", todo.Key),
new SQLiteParameter("#Name", table.Name),
new SQLiteParameter("#IsComplete", table.IsComplete) };
if (!string.IsNullOrWhiteSpace(someValueToCheck)) {
//Replace 'someValueToCheck' with a value for the C# that you want to use as a parameter.
tableAList.Add(new SQLiteParameter("#OtherFieldValue", someValueToCheck));
}
//We convert the list back to an array as it is the expected parameter type.
command.Parameters.AddRange(tableAList.ToArray());
rows = command.ExecuteNonQuery();
}
DB_CONNECTION.Close();
return (rows);
}
In this day and age it would probably be worth looking into LINQ to Entities, as this will help you to compose queries dynamically in your code - for example https://stackoverflow.com/a/5541505/201648.
To setup for an existing database - also known as "Database First" - see the following tutorial:
https://msdn.microsoft.com/en-au/data/jj206878.aspx
You can skip step 1 since you already have a database, or do the whole tutorial first as practice.
Here is some psuedo-C# LINQ code to perform roughly the same update as the previous example:
//The context you have setup for the ERP database.
using (var db = new ERPContext())
{
//db is an Entity Framework database context - see
//https://msdn.microsoft.com/en-au/data/jj206878.aspx
var query = db.MyTable
.Where(c => c.Key == todo.Key);
if (!string.IsNullOrWhiteSpace(someValueToCheck))
{
//This where is used in conjunction to the previous WHERE,
//so it's more or less a WHERE condition1 AND condition2 clause.
query = query.Where(c => c.SomeOtherField == someValueToCheck);
}
//Get the single thing we want to update.
var thingToUpdate = query.First();
//Update the values.
thingToUpdate.Name = table.Name;
thingToUpdate.IsComplete = table.IsComplete;
//We can save the context to apply these results.
db.SaveChanges();
}
There is some setup involved with Entity Framework, but in my experience the syntax is easier to follow and your productivity will increase. Hopefully this gets you on the right track.
LINQ to Entites can also map SQL stored procedures if someone one your team objects to using it for performance reasons:
https://msdn.microsoft.com/en-us/data/gg699321.aspx
OR if you absolutely ust compose custom queries in the C# code this is also permitted in Entity Framework:
https://msdn.microsoft.com/en-us/library/bb738521(v=vs.100).aspx
In a EF6 context, I want to filter multiples entities by dynamic fields/attributes. I'm new to EF and my perspective is very corrupted by T-SQL and stored procedures and dynamic SQL queries.
For instance in a ERP environment, the user can filter by a code, and the system should return the:
Customer with CustomerID = code
Supplier with SupplierID = code
User with UserID = code
Orders with CustomerID/SupplierID = code
etc.
But can not only be a code, can multiples concepts to filter for: a name, a city, a date, ... and may all not apply to all the entities.
So since each entity has different attributes names to refer to that "code" concept, I've thought that the best solution is to use EntityCommand instead of LinQ.
And the code should look something like:
// Create a query that takes two parameters.
string eSqlCustomerQuery =
#"SELECT VALUE Contact FROM AdventureWorksEntities.Customer AS Customer";
string eSqlCustomerQuery =
#"SELECT VALUE Contact FROM AdventureWorksEntities.Customer AS Customer";
// Create a list of parameters
var param = new SortedList<string, EntityParameter>();
// for each clauses add a pamater and build the query command dynamically.
if(!code)
{
eSqlCustomerQuery += "WHERE Customer.CustomerID = #CODE";
eSqlSupplierQuery += "WHERE Supplier.SupplierID = #CODE";
//... more entities to
param["CODE"].ParameterName = "CODE";
param["CODE"].Value = code;
}
// more parameters here...
using (EntityConnection conn =
new EntityConnection("name=AdventureWorksEntities"))
{
conn.Open();
using (EntityCommand cmd = new EntityCommand(eSqlCustomerQuery, conn))
{
cmd.Parameters.Add(param["CODE"]);
cmd.Parameters.Add(param["DATE"]);
// more parameters here...
}
// the same for each query...
// ...
// run all the queries ...
// ...
// Etc.
conn.Close();
}
My questions are 3:
At the time I'm doing cmd = new EntityCommand(eSqlCustomerQuery, conn) can I use something like the System.Data.SqlClient.SqlCommandBuilder.DeriveParameters(cmd);?
Since this dynamic query it's so dynamic that it can be cached or have a reusable execution plan, how can it be improved?
Is it possible to do it with LinQ in a cleaner way?
Use LINQ like that:
//define base LINQ
Contracts = from R in AdventureWorks.Customer select R; //there is IQueryable, not actually materialized
//tune filters, no records will fetched
Result = Contracts;
if (code!=null) Result = Result.Where(_=>_.Code==code);
if (date!=null) Result = Result.Where(_=>_.Date==date);
//materialize records
Records = Result..Select(_=>_.Contract).ToArray();
If I have the name of a database table like this:
string tableName = "Addresses";
string tableName = "Customers";
How can I construct a dynamic LINQ statement like this:
var items = from o in db.{tableName}
select o;
foreach (var item in items)
{
sb.Append(item.Id + Environment.NewLine);
}
I know I could do something like this:
IEnumerable<Customer> results = db.ExecuteQuery<Customer>
("SELECT contactname FROM customers WHERE city = {0}",
"London");
But in this instance I don't want strongly typed objects as my result, I just want a recordset to pick apart.
Answer:
Thanks Shalkalpesh, I took your advice and solved this by just avoiding LINQ altogether:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["main"].ToString();
conn.Open();
string sql = "SELECT * FROM " + tableName;
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataTable dtResult = new DataTable();
da.Fill(dtResult);
foreach (DataRow drRow in dtResult.Rows)
{
Console.WriteLine(drRow["Id"].ToString());
}
da.Dispose();
conn.Close();
conn.Dispose();
If you want the recordset, you can access the Connection property of the DataContext class (db variable in your context) and use it to execute regular query and get the result in either of DataTable or DataReader.
You can use the Dynamic Linq Query library (or D-Linq for short).
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Sorry - I'm away from a dev machine at the moment, but would this help?
It seems to suggest you should use DynamicQuery ...
Another way - as was mentioned by
several commenters in my previous post
- is to use DynamicQuery. DynamicQuery is one of the samples installed with
the 101 LINQ samples and you can find
it by clicking on Help | Samples in
Visual Studio. If you drill into the
sample folders there's a DynamicQuery
sample project, which basically
consists of a class that provides
string based lambda expression
parsing.
The class DynamicQuery class is self
contained and you can simply add it to
your project. It provides additional
extension methods that let you use
string expressions for various of the
query methods including the .Where()
method (but unfortunately for the
above example not the .Single()
method). So with Dynamic Query the
above .Load() method can also be
written as follows:
There's an actual code example on the post, too...
LINQ to SQL is meant to be strongly typed so I don't think you can use LINQ to SQL to use dynamic table names unless you use ExecuteQuery
Thanks
I don't think Dynamic Linq is the solution here.
As far as I know, there is no solution to your problem.
Even with dynamic linq, the compiler would need to somehow figure out what table the string refers to at compile time to allow strong typing of its members.
For instance, let's say you have two tables:
Product {Id, Name, Value}
Customer {Id, Firstname, Surname, Address, Email, ...}
And you use Linq-to-SQL as your ORM:
var items = from p in MagicTableResolver("Product")
where p.Firstname // <-- How could intellisense allow this?
select p;
var items = from c in MagicTableResolver("Customer")
where c.Name // <-- It can't, it cannot be strongly typed
select c;
Building off of this and this, here's how to run some some LINQ commands on a string tablename. I haven't figured out how to get the query syntax working (like "FROM" and "SELECT"), but you can still get and insert rows.
Type tableType = Assembly.GetExecutingAssembly().GetType("NameSpace.TableName");
ITable itable = dbcontext.GetTable(tableType);
//prints contents of the table
foreach (object y in itable) {
string value = (string)y.GetType().GetProperty("ColumnName").GetValue(y, null);
Console.WriteLine(value);
}
//inserting into a table
dynamic tableClass = Activator.CreateInstance(tableType);
//Alternative to using tableType
dynamic tableClass = Activator.CreateInstance(null, "NameSpace.TableName").Unwrap();
tableClass.Word = userParameter;
itable.InsertOnSubmit(tableClass);
dbcontext.SubmitChanges();
//sql equivalent
dbcontext.ExecuteCommand("INSERT INTO [TableName]([ColumnName]) VALUES ({0})", userParameter);
I'm trying to find optimal (fast vs easiest) way to access SQL Server code thru code in C#.
As I was learning from books I've encountered multiple suggestions usually telling me to do it via drag and drop. However since I wanted to do it in code first approach was to get data by column numbers, but any reordering in SQL Query (like adding/removing columns) was pain for me to fix.
For example (don't laugh, some code is like 2 years old), I even coded special function to pass sqlQueryResult and check if it's null or not):
public static void exampleByColumnNumber(string varValue) {
string preparedCommand = #"SELECT TOP 1 [SomeColumn],[SomeColumn2]
FROM [Database].[dbo].[Table]
WHERE [SomeOtherColumn] = #varValue";
SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
sqlQuery.Prepare();
sqlQuery.Parameters.AddWithValue("#varValue) ", varValue);
SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
if (sqlQueryResult != null) {
while (sqlQueryResult.Read()) {
string var1 = Locale.checkForNullReturnString(sqlQueryResult, 0);
string var2 = Locale.checkForNullReturnString(sqlQueryResult, 1);
}
sqlQueryResult.Close();
}
}
Later on I found out it's possible thru column names (which seems easier to read with multiple columns and a lot of changing order etc):
public static void exampleByColumnNames(string varValue) {
string preparedCommand = #"SELECT TOP 1 [SomeColumn],[SomeColumn2]
FROM [Database].[dbo].[Table]
WHERE [SomeOtherColumn] = #varValue";
SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
sqlQuery.Prepare();
sqlQuery.Parameters.AddWithValue("#varValue) ", varValue);
SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
if (sqlQueryResult != null) {
while (sqlQueryResult.Read()) {
string var1 = (string) sqlQueryResult["SomeColumn"];
string var2 = (string) sqlQueryResult["SomeColumn2"];
}
sqlQueryResult.Close();
}
}
And 3rd example is by doing it by column names but using .ToString() to make sure it's not null value, or by doing If/else on the null check.
public static void exampleByColumnNamesAgain(string varValue) {
string preparedCommand = #"SELECT TOP 1 [SomeColumn],[SomeColumn2], [SomeColumn3]
FROM [Database].[dbo].[Table]
WHERE [SomeOtherColumn] = #varValue";
SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
sqlQuery.Prepare();
sqlQuery.Parameters.AddWithValue("#varValue) ", varValue);
SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
if (sqlQueryResult != null) {
while (sqlQueryResult.Read()) {
string var1 = (string) sqlQueryResult["SomeColumn"].ToString();
DateTime var2;
DateTime.TryParse(sqlQueryResult["SomeColumn2"].ToString());
int varInt = ((int) sqlQueryResult["SomeColumn3"] == null ? 0 : (int) sqlQueryResult["SomeColumn3"];
}
sqlQueryResult.Close();
}
}
Please bare in mind that I've just created this for sake of this example and there might be some typos or some slight syntax error, but the main question is which approach is best, which is the worst (I know first one is the one that I dislike the most).
I will soon have to start / rewriting some portion of my little 90k lines app which has at least those 3 examples used widely, so i would like to get best method for speed and preferably easiest to maintain (hopefully it will be same approach).
Probably there are some better options out there so please share?
It seems you may be looking at old books. If you're going to do it the "old fashioned way", then you should at least use using blocks. Summary:
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(commandString, connection))
{
using (var reader = command.ExecuteReader())
{
// Use the reader
}
}
}
Better still, look into Entity Framework.
Links: Data Developer Center
If it's easy you're looking for, you can't do any better than Linq-to-SQL:-
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
If your SQL database already exists, you can be up-and-running in seconds.
Otherwise, I agree with John.
you should have a look into these tutorials,
[http://www.asp.net/learn/data-access/][1]
All the work you are planning is already been done.
have a look at this way of doing same what you are doinng
string preparedCommand =
#"SELECT TOP 1 [SomeColumn],[SomeColumn2], [SomeColumn3]
FROM [Database].[dbo].[Table]
WHERE [SomeOtherColumn] = #varValue";
[1]: http://www.asp.net/learn/data-access/
More better way of doing the same above is by Using LINQ TO SQL
var result = from someObject in SomeTable
where SomeColumnHasValue == ValueToCompare
select new { SomeColumn, SomeColumn1, SomeColumn2};
No Type Safety Issues
Visualise Database in C# while you
work on it
at compile time less errors
less code
more productive
Following are some of the great resources for LINQ if you are interested
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
http://www.hookedonlinq.com/MainPage.ashx
https://stackoverflow.com/questions/47740/what-are-some-good-linq-resouces
Hope it helps
If you're looking into using just straight ADO.net you might want to go out and find Microsoft's Enterprise Library's Data Access Application Block . David Hayden has a decent article that goes into some detail about using it.
Good luck and hope this helps some.
The easiest way to do data access in C#, to my mind, is using typed DataSets. A lot of it really is drag-and-drop, and it's even easier in .NET 2.0+ than in .NET 1.0/1.1.
Have a look at this article, which talks about using typed DataSets and TableAdapters:
Building a DAL using Strongly Typed TableAdapters and DataTables in VS 2005 and ASP.NET 2.0
A typed DataSet is basically a container for your data. You use a TableAdapter to fill it (which happens with SQL or stored procs, whichever you prefer) and to update the data afterwards. The column names in each DataTables in your DataSet are autogenerated from the SQL used to fill them; and relations between database tables are mirrored by relations between DataTables in the DataSet.
Don't convert data to strings only to try to parse it; DataReaders have methods to convert SQL data to .Net data types:
using (var connection = new SqlConnection(Locale.sqlDataConnection))
using (var command = new SqlCommand(preparedCommand, connection))
using (var reader = command.ExecuteReader())
{
int stringColumnOrdinal = reader.GetOrdinal("SomeColumn");
int dateColumnOrdinal = reader.GetOrdinal("SomeColumn2");
int nullableIntColumnOrdinal = reader.GetOrdinal("SomeColumn3");
while (reader.Read())
{
string var1 = reader.GetString(stringColumnOrdinal);
DateTime var2 = reader.GetDateTime(dateColumnOrdinal);
int? var3 = reader.IsDBNull(nullableIntColumnOrdinal) ? null : (int?)reader.GetInt32(nullableIntColumnOrdinal);
}
}
I test the many different ways for get data from sql server database and i faced & found fastest way is following:
First of all create class with "IDataRecord" parameterized method as per your required properties.
class emp
{
public int empid { get; set; }
public string name { get; set; }
public static emp create(IDataRecord record)
{
return new emp
{
empid = Convert.ToInt32(record["Pk_HotelId"]),
name = record["HotelName"].ToString()
};
}
}
Now create method for get data as below:
public List<S> GetData<S>(string query, Func<IDataRecord, S> selector)
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = query;
cmd.Connection.Open();
using (var r = cmd.ExecuteReader())
{
var items = new List<S>();
while (r.Read())
items.Add(selector(r));
return items;
}
}
}
And then call function like:
var data = GetData<emp>("select * from employeeMaster", emp.create);