Can an IOrderedEnumerable bindingsource be created from a DBSet? - ef-code-first

I want to dynamically specify a number of columns to sort by.
My code is as follows
var dset = Context.People;
var QuickSearch = "a";
var qry = dset.Where( p => p.LastName.Contains(QuickSearch) );
qry.Load();
BindingSource bindingsource;
bindingSource.DataSource = dset.Local.ToBindingList();
I want to use the technique in the answer outlined
here
Thus I should be able to do something like ( simplified )
IQueryable<Person> qry = null;
qry = base.Context.People.OrderBy(x=>x.FirstName); // this is OK
qry = qry.ThenBy(y=>y.LastName); // This wont compile
However it doesn't compile.
[Update]
Since ThenBy is an extension method for IOrderable My question becomes
Can an IOrderedEnumerable bindingsource be created from a DBSet?

change it to be like this:
var qry = base.Context.People.OrderBy(x=>x.FirstName);
qry = qry.ThenBy(...)
or
IOrderedQueryable<Person> qry = null;
qry = base.Context.People.OrderBy(x=>x.FirstName);
qry = qry.ThenBy(y=>y.LastName);
The reason is that you are declaring qry as IQueryable, when ThenBy is an extension method for IOrderedQueryable (which is what OrderBy returns)

Related

Convert date in SQLite?

I created an scheduler application with SQL server and now i want to make another one using SQLite. I have a convert query in SQL and it does not work in SQLite. Can anyone help?
try
{
ObservableCollection<Classes.EventClass> listEvents = new ObservableCollection<EventClass>();
SQLiteConnection conn = new SQLiteConnection(#"Data Source=Scheduler.db;Version=3;");
string query= "Select * from Sche_Event where CONVERT(DATE,Event_TimeFrom) = CONVERT(DATE,'" +d.ToString("yyyy-MM-dd HH:mm:ss") + "') ORDER BY Event_TimeFrom ASC";
SQLiteCommand command= new SQLiteCommand(query, conn);
conn.Open();
SQLiteDataReader dr = command.ExecuteReader();
while (dr.Read())
{
EventClass dog = new EventClass();
dog.DogID = dr.GetInt32(0);
dog.DogName = dr.GetString(1);
dog.DogText = dr.GetString(2);
dog.DogPriority = dr.GetInt32(3);
dog.DogTimeFrom = dr.GetDateTime(4);
dog.DogTimeTo = dr.GetDateTime(5);
dog.KliID = dr.GetInt32(6);
listEvents .Add(dog);
}
return listEvents ;
}
catch (Exception)
{
return null;
}
I expect that my code goes to While() and read the information about the Event but all it does it goes to Catch() and returns nothing.
The query in SQL works just fine but i dont not work with SQLite :(
Of course the statement doesn't work in SQLite, because convert() is not a known function there. But if you're lucky you don't even need it, depending on the format in which the timestamp is stored in your SQLite table. As you didn't provide any sample data nor described what you actually want to do, you could either read the SQLite doc about date and time functions or rephrase your question to "How do I do X in SQLite?".

Passing a user defined table type to SQL function in Ormlite

I've to pass a table to a SQL function (till now I've passed to stored procedures and everything was fine)
Consider the following snippet
var dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("ID", typeof(Guid)));
foreach (var o in orders)
{
var r = dataTable.NewRow();
r["ID"] = o;
dataTable.Rows.Add(r);
}
var res = db.Exec(cmd =>
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("INPUT", dataTable));
cmd.CommandText = "SELECT * FROM FUNCTION";
return cmd.ConvertToList<MyObj>();
});
I'm not aware if parameters are considered when specifing CommandType as Text, I've tried on SQLServer and it works...
What am I doing wrong? is this a limitation of ServiceStack's OrmLite?
Thanks
When manually populating cmd as in your example you're using ADO.NET (i.e. not OrmLite), so you need to find out the correct way to call a SQL Server function from ADO.NET.
It seems you can only pass a datatable to a UDF from SQL Server 2008+ and requires that your TableType parameter is READONLY.

cshtml file - Locate current windows user, then query database

I am working on a localhost site that queries, and updates a database. I have not worked with ASP.NET very much.
I am wondering if it would be possible to find out the current windows user, then select all records in the database that match the located username.
I know how to do this with vbscript, but I need to make it work in a cshtml file.
How do I locate the user?
What would my select sentence look like?
Any help or suggestions are appreciated.
Thanks.
Edit:
Here is the code that I use to display data from a specific user:
#{
var db = Database.Open("Database") ;
var selectCommand = "SELECT * FROM Table WHERE UserID = 'asmith'";
var searchTerm = "";
var selectedData = db.Query(selectCommand, searchTerm);
var grid = new WebGrid(source: selectedData, defaultSort: "Team", rowsPerPage:20);
}
When I change WHERE UserID = 'asmith' to WHERE UserID = #Environment.UserName, I receive the error:
There was an error parsing the query. [ Token line number = 1,Token line offset = 48,Token in error = . ] and the below is highlighted in red.
Line 15: var selectedData = db.Query(selectCommand, searchTerm);
Edit #2:
This Successfully queries the database and returns the correct data, but isn't clean and is causing an issue with another query on the page.
var CurrUser = Environment.UserName;
var db = Database.Open("Database") ;
var selectCommand = "SELECT * FROM Table WHERE UserID = #0";
var searchTerm = #CurrUser;
You're missing the single quotes:
var selectCommand = "SELECT * FROM Table WHERE UserID = 'asmith'";
should be:
var selectCommand = "SELECT * FROM Table WHERE UserID = '#" + Environment.UserName + "'";
Environment.UserName is a string. You're querying where UserID. Are you sure UserID shouldn't be an int or some uniqueidentifier?
Just to clean up and resolve an old post, I would change the select to something more like this:
var currentUser = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(#"\") + 1);
var selectCommand = "SELECT * FROM Table WHERE UserID = #0";
var selectedData = db.Query(selectCommand, currentUser);

How do I get a SP into a string?

I Dont know how to get my stored Procedures value into a String.
This is my guess but dosent work:
string id = Request.QueryString["ProductID"];
String Color = GetColor(id);
The GetColor(id) should be blue, but is "", and my String Color is "".
public static DataTable GetColor(string ProductID)
{
DbCommand comm = GenericDataAccess.CreateCommand();
comm.CommandText = "GetColor";
DbParameter param = comm.CreateParameter();
param.ParameterName = "#ProductID";
param.Value = ProductID;
param.DbType = DbType.Int32;
comm.Parameters.Add(param);
DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
return table;
}
ALTER PROCEDURE GetColor
#ProductID INT AS Select Color from tblColor where ProductID = #ProductID
I would guess that it's because your method is returning a DataTable, which doesn't cast directly to a string. I think something like GetColor(id).Rows[0][0] would work?
You should probably use ExecuteScalar here -- no reason at all to create a datatable to get a single value.
Can you set a breakpoint at return table; and inspected the returned result.
If the table is filled correctly then you will need to use
String Color = GetColor(id).Rows[0][0];
For your comment:
DataTable result = GetColor(id);
string Color = result.Rows[0][0];
string Price = result.Rows[0][1];
string Width = result.Rows[0][2];
But you need to inspect the result DataTable and its first row to make sure you have populated it correctly. Try to inspect result.Rows[0] in the quick watch window

Parameterized query in Oracle trouble

I'm using Oracle.DataAccess rather than the obsolete System.Data.OracleClient and I seem to be having trouble passing multiple parameters to my update query
This works
OracleCommand.CommandText = "UPDATE db SET column1 = :param1 WHERE column2 = 'Y'"
OracleCommand.Parameters.Add(New OracleParameter("param1", "1234"))
But I want to be able to pass multiple parameters
Here's my full code
OracleConn.Open()
OracleCommand = OracleConn.CreateCommand()
OracleCommand.CommandText = "UPDATE db SET column1 = :param1 WHERE column2 = :param2"
OracleCommand.CommandType = CommandType.Text
OracleCommand.Parameters.Add(New OracleParameter("param1", "1234"))
OracleCommand.Parameters.Add(New OracleParameter("param2", "Y"))
OracleCommand.ExecuteNonQuery()
My SELECT query seems to work when passing multiple parameters but not the update one
Although I can't see anything wrong with your example, I wonder if you're being hit by the old BindByName problem. By default, ODP.NET binds parameters to the query in the order in which they are added to the collection, rather than based on their name as you'd like. Try setting BindByName to true on your OracleCommand object and see if that fixes the problem.
I've had this problem so many times that I use my own factory method to create commands which automatically sets this property to true for me.
Classic useless Oracle documentation here
To emulate the default behavior of the System.Data.OracleClient, you should set the OracleCommand to bind by name.
OracleCommand.BindByName = True
Try newing up your OracleParameter with a the type specified. Set the value of the object before adding it to the parameters list.
var param1 = new OracleParameter( "param1", OracleType.Int32 );
param1.Value = "1234";
OracleCommand.Parameters.Add( param1 );
Try this, hope it works. It does compile.
Not sure if you also have to send a commit...
I always do this sort of thing through a stored procedure, so I have a commit after the update statement in the stored procedure.
Harvey Sather
OracleConnection ora_conn = new OracleConnection("connection string");
OracleCommand ora_cmd = new OracleCommand("UPDATE db SET column1 = :param1 WHERE column2 = :param2", ora_conn);
ora_cmd.CommandType = CommandType.Text;
ora_cmd.BindByName = true;
ora_cmd.Parameters.Add(":param1", OracleDbType.Varchar2, "1234", ParameterDirection.Input);
ora_cmd.Parameters.Add(":param2", OracleDbType.Varchar2, "Y", ParameterDirection.Input);
ora_cmd.ExecuteNonQuery();
The first code block is correct: use a colon in front of the parameter name, but not in the first argument to OracleParameter.
If no errors are thrown, it could be that the UPDATE runs successfully, it just doesn't update any records based on the WHERE clause and its substituted parameter value. Try doing it on a test table with no WHERE clause in the UPDATE to make sure it does something.
Here's the type of structure I usually use (sorry, this is from memory) :
int rows = 0;
using ( OracleConnection conn = new OracleConnection(connectionString) ) {
using ( OracleCommand cmd = conn.CreateCommand() ) {
cmd.CommandText = "UPDATE table SET column1 = ':p1 WHERE column2 = :p2";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(":p1", p1Val);
cmd.Parameters.AddWithValue(":p2", p2Val);
rows = cmd.ExecuteNonQuery();
}
}
The key difference is the use of the AddWithValue - I don`t remember why I ended up using that, but do remember having problems with some of the other ways of doing it.

Resources