TableAdapter Query with optional WHERE paramerter - c#

I am trying to create a TableAdapter query with an optional WHERE parameter.
This is my query:
SELECT Productos.Categoria, Productos.Subcategoria, Productos.Nombre,
Productos.Marca, Productos.Descripcion, Proveedores.Nombre AS Proveedor, Precios.Precio
FROM Precios, Productos, Proveedores
WHERE Precios.Producto_ID = Productos.ID AND Precios.Proveedor_ID =
Proveedores.ID AND Proveedores.Nombre = ?
I would like "Proveedores.Nombre = ?" to be optional or if ? = null or nothing, the query does not filter by Proveedores.Nombre
I have tried this:
(Proveedores.Nombre =#PNombre OR #PNombre = NULL)
But I have got an error:
Generated SELECT statement:
Error in WHERE clause near '#'.
Unable to parse the query text
Thank you very much for you help,
Regards
Andres
EDIT:
I ma in a windows form project. I am using a DataSource - DataSet linked to my access database. So to create FillBy() and GetData() I use a table-adapter which was automatically created when I inserted the DataSource to my WindowsForm.
This is the method created liked to the GetData() I am using:
public virtual DB_ProvProd2DataSet.ProductosDataTable GetDataByTodo(string Nombre) {
this.Adapter.SelectCommand = this.CommandCollection[5];
if ((Nombre == null)) {
throw new global::System.ArgumentNullException("Nombre");
}
else {
this.Adapter.SelectCommand.Parameters[0].Value = ((string)(Nombre));
}
DB_ProvProd2DataSet.ProductosDataTable dataTable = new DB_ProvProd2DataSet.ProductosDataTable();
this.Adapter.Fill(dataTable);
return dataTable;
}
Where this.CommandCollection[5] = the query and this.Adapter.SelectCommand.Parameters[0] is the input related to the '?' of the query.
I hope this helps!
Thanks!!!

Try assing it to a local variable:
string tmp= #PNombre
(Proveedores.Nomber==tmp || tmp == null)

Related

How to handle out of bound exception inside Json object?

I have a function that is returning a Json object as follows:
return Json(
db.Select(c => new GridViewModel()
{
Number = c.Rows[0][0].ToString(),
DocId = c.Rows[0][1].ToString(),
PartyName = c.Rows[0][2].ToString(),
FilingType = c.Rows[0][3].ToString(),
FilingDate = c.Rows[0][4].ToString(),
}
).ToDataSourceResult(request));
db is a DataTable object, currently I just have one row so I am using index=0. I keep getting error massage in vs saying "An exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll but was not handled in user code"
Is there a way how to add try catch inside a Json object?
Thanks
DataTable doesn't have .Select(Func<...>) method.
it has DataTable.Select(string filterExpression), so it is very similar what you have in SQL e.g.
Select * from MyTable WHERE Column1 = 'something'
for DataTable it will be
var myFilteredRows = myDataTable.Select("Column1 = 'something'")
Please visit MSDN for more info.
According to your code I assume you want to use LINQ Enumerable.Select on non-enumerable object. Which is impossible :)
So, if you have DataSet then you can do this
DataSet myDataSet = init from database
then
dataSet.Tables.Cast<System.Data.DataTable>().Select(table => new YourObject
{
init your object here, to get rows do this
MyRows = table.Rows.Cast<System.Data.DataRow>().Select(row => MyRowObject
{
init row object here
})
});
If you have only one DataTable (not DataSet)
then
table.Rows.Cast<System.Data.DataRow>().Select(row => GridViewModel
{
Number = row[0].ToString(),
DocId = row[1].ToString(),
PartyName = row[2].ToString(),
FilingType = row[3].ToString(),
FilingDate = row[4].ToString(),
});
Also I highly recommend to use column names and not indexes to avoid confusion in the future.
Hope this helps.

Deleting in Db4o Database Using Linq

I have a problem with deleting from my Db4o database. At the moment i can store new objects and get them shown in a datagrid view. But for some reason i cannot delete the objects again. Here is the Linq i am using.
public void DeleteStudent(int ssn)
{
var config = Db4oFactory.NewConfiguration();
using (var db = Db4oFactory.OpenFile(config, "StudentDB"))
{
var query = (from StudentDB x in db
where x.SSN == ssn
select x);
if (query != null)
{
db.Delete(query);
}
}
}
I am getting the object that i want to delete by the ssn. I have tried debug and check that its not null and its not. I am getting the right object.
Here is the GUI part i am using.
private void btnDeleteStudent_Click(object sender, EventArgs e)
{
int ssn = Convert.ToInt32(txtSSN.Text);
studentDB.DeleteStudent(ssn);
gridStudents.DataSource = studentDB.GetAllStudents();
ClearBoxes(this);
}
i am getting the ssn from a textbox and giving it as a parameter when i click the delete button. And after that i am refreshing the gridview.
Hope one of you can help! i am new to Db4o so dont know a lot about it.
You are passing the wrong object to the db.
change your code to something like:
using (var db = Db4oFactory.OpenFile(config, "StudentDB"))
{
var query = (from StudentDB x in db
where x.SSN == ssn
select x).SingleOrDefault();
if (query != null)
{
db.Delete(query);
}
db.Commit();
}

C# Linq-SQL query result returning nothing

I'm fairly new to LINQ (and SQL at that). When trying to query my SQL Database in C# "Supervisors" (which contains only one column "Names" made of nvarchar(50) variables, none of which are Null), supvName ends up being an empty list. If I don't cast it as a List, supvName is of typeSystem.Data.EnumerableRowCollection<string> if that helps.
public addNewEmp()
{
InitializeComponent();
using (TestDataSet db = new TestDataSet())
{
var supvName = (from n in db.Supervisors
select n.Names).ToList();
foreach (string n in supvName)
{
supv_cbox.Items.Add(n);
}
}
}
Even when using a Where statement, that one result doesn't show up, so I'm sure it's something simple in my code that I just can't seem to figure out. I've already tried using AsEnumerable() which didn't change anything.
EDIT: I'm doing this in VS 2010 WPF. Also when I Preview Data in TestDataSet.xsd, it does return the all the data in the Database.
Solution: The problem was when I used a DataSet. When I used a DataContext instead it worked perfectly fine. Thanks to your DataSet or DataContext question lazyberezovsky or I never would have tried that.
Using the following works:
var supvName = db.Supervisors.Select(m => m.Names);
supv_cbox.ItemsSource = supvName;
Thanks Surjah Singh too.
When you are enumerating over DataTable with Linq to DataSet, you should call AsEnumerable() on datatable and use Field<T> extension to get column value:
var supvName = (from r in db.Supervisors.AsEnumerable()
select r.Field<string>("Names")).ToList();
BTW query variable r will be of DataRow type.
Your code can be simplified to:
var names = db.Supervisors.AsEnumerable().Select(r => r.Field<string>("Names"));
supv_cbox.DataSource = names.ToList();
//Var supvName = Supervisors.Select(m=>m.Names);
var supvName = from s in Supervisors.Tables[0].AsEnumerable()
select s.Field<string>("Names");

C# SMO Select from Database

I have been racking my brain trying to figure out how to execute a SELECT from Table using SMO in C# and returning that value to a string item.
I have seen multiple posts of how I can run a SQL script from within C# which is not what I want to do. Here is the code I have so far
public static void GetDealerInfo()
{
Server databaseServer = new Server(dbServer);
try
{
databaseServer.ConnectionContext.LoginSecure = dbSecure;
databaseServer.ConnectionContext.Login = dbUser;
databaseServer.ConnectionContext.Password = dbPass;
databaseServer.ConnectionContext.Connect();
sDealerName = databaseServer.ConnectionContext.ExecuteWithResults("USE DATABASE Select DataValue from TABLE where KEYField = 'DealershipName'").ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
if (databaseServer.ConnectionContext.IsOpen)
{
databaseServer.ConnectionContext.Disconnect();
}
}
}
I also have a string called sDealerName which is where I want to pull, all I am getting is
sDealerName = System.Data.DataSet
Can anyone point me in the correct direction?
UPDATE:
Here is the code to get it going or at least what worked for me
try
{
databaseServer.ConnectionContext.LoginSecure = dbSecure;
databaseServer.ConnectionContext.Login = dbUser;
databaseServer.ConnectionContext.Password = dbPass;
databaseServer.ConnectionContext.DatabaseName = dbDatabase;
databaseServer.ConnectionContext.Connect();
DataSet dsName = databaseServer.ConnectionContext.ExecuteWithResults("Select DataValue from ABSetup where KEYField = 'DealershipName'");
sDealerName = dsName.Tables[0].Rows[0][0].ToString();
DataSet dsNum = databaseServer.ConnectionContext.ExecuteWithResults("Select DataValue from ABSetup where KEYField = 'ABOfficeCID'");
sDealerNumber = dsNum.Tables[0].Rows[0][0].ToString();
}
Change your code to:
DataSet ds = databaseServer.ConnectionContext.ExecuteWithResults("Select DataValue from TABLE where KEYField = 'DealershipName'");
The "USE DATABASE;", first, you may not need it. Second it, if you mean "USE MyDatabaseName;" , try it with a semi colon after the name.
More important to your question : then do a
Console.Writeline (ds.GetXml );
You'll then "see" the DataSet, the DataTable, the row inside the DataTable from which to "pluck" your scalar value.
string value = string.Empty;
if(null!=ds) {
if(null!=ds.Tables) {
if(ds.Tables.Count > 0) {
if(null!=ds.Tables[0].Rows) {
if(ds.Tables[0].Rows.Count > 0) {
if(null!=ds.Tables[0].Rows[0].Columns){
if(ds.Tables[0].Rows[0].Columns.Count > 0)
{
value = ds.Tables[0].Rows[0].Columns[0].Value;
}}}}}}}
"Count" may be "Length", I'm going from memory.
My code is untested from memory, so take it with a grain of salt.
You're calling ToString() on the object instance which is why you're getting the fullly qualified type name.
The value you're looking for will be inside a DataTable object within the DataSet. Run you're code again and break on the sDealerName line. Then using the magnifying glass tool click on that to open the dataset viewer and you'll be able to figure the rest out from there.

how to check if a datareader is null or empty

I have a datareader that return a lsit of records from a sql server database. I have a field in the database called "Additional". This field is 50% of the time empty or null.
I am trying to write code that checks if this field isnull. The logic behind this is:
If the field "Additional" contains text then display the info otherwise hide the field.
I have tried:
if (myReader["Additional"] != null)
{
ltlAdditional.Text = "contains data";
}
else
{
ltlAdditional.Text = "is null";
}
The above code gives me this error:
Exception Details: System.IndexOutOfRangeException: Additional
Any help would be greatly appreciated...
See Also:
Check for column name in a SqlDataReader object
if (myReader["Additional"] != DBNull.Value)
{
ltlAdditional.Text = "contains data";
}
else
{
ltlAdditional.Text = "is null";
}
if (myReader.HasRows) //The key Word is **.HasRows**
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null Or Empty";
}
I haven't used DataReaders for 3+ years, so I wanted to confirm my memory and found this. Anyway, for anyone who happens upon this post like I did and wants a method to test IsDBNull using the column name instead of ordinal number, and you are using VS 2008+ (& .NET 3.5 I think), you can write an extension method so that you can pass the column name in:
public static class DataReaderExtensions
{
public static bool IsDBNull( this IDataReader dataReader, string columnName )
{
return dataReader[columnName] == DBNull.Value;
}
}
Kevin
This is the correct and tested solution
if (myReader.Read())
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null";
}
I also use OleDbDataReader.IsDBNull()
if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }
First of all, you probably want to check for a DBNull not a regular Null.
Or you could look at the IsDBNull method
In addition to the suggestions given, you can do this directly from your query like this -
SELECT ISNULL([Additional], -1) AS [Additional]
This way you can write the condition to check whether the field value is < 0 or >= 0.
#Joe Philllips
SQlDataReader.IsDBNull(int index) requires the ordinal number of the column. Is there a way to check for nulls using Column Name, and not it's Ordinal Number?
Try this simpler equivalent syntax:
ltlAdditional.Text = (myReader["Additional"] == DBNull.Value) ? "is null" : "contains data";
I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:
DataTable dt = new DataTable();
dt.Rows[0].Table.Columns.Contains("SampleColumn");
using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.
This
Example:
objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";
Best thing to get this done in query. However, if query bond to other functions than checking DBNull.Value in while loop would address the issue.
if (reader.HasRows)
{
while (reader.Read())
{
(reader["Additional"] != DBNull.Value) ? "contains data" : "is null";
}
}
AMG - Sorry all, was having a blond moment. The field "Additional" was added to the database after I had initially designed the database.
I updated all my code to use this new field, however I forgot to update the actual datareader code that was making the call to select the database fields, therefore it wasn't calling "Additional"

Categories