I have a dataset (myds) that contains table (assests).
When I try to find a row in (assest) by using the auto-generated FindBy() it always returns null.
MyDS.AssestsRow asRow = this.myds.Assests.FindBy(pk1,pk2,pk3);
if (asRow == null)
return "No Row Found";
I'm 100% sure that I have row in the table that matches my query but this FindBy() always returns null!
Any ideas?
Here we go,
Although I couldn't figure it out yet but I found that after declaring Assets datatable and using AssetsTableAdapter to get data into it, only then, I was able to retrieve the row I wanted.
So instead of doing this:
MyDS.AssestsRow asRow = this.myds.Assests.FindBy(pk1,pk2,pk3);
if (asRow == null)
return "No Row Found";
I did that:
MyDS.AssestsDataTable assetsDataTable = this.assestsTableAdapter.GetData();
MyDS.AssestsRow asRow = assetsDataTable.FindBy(pk1,pk2,pk3);
if (asRow == null)
return "No Row Found";
Anyone could tell me WHY?
Related
I use Entity frameWork to save new row to my database.
I created method that insert new object to the table.The object is added to the table but method returns me always 0 .While I expect the new Id.
Here is the method:
private int SaveVectorLayer(VVectorLayer layer)
{
if (layer == null) return 0;
Data.VectorLayer vectorLayer;
if (layer.Id == 0)
{
vectorLayer = new Data.VectorLayer();
_context.Entry(vectorLayer).State = EntityState.Added;
}
else
{
vectorLayer = _context.VectorLayers.Find(layer.Id);
if (vectorLayer == null) throw new ObjectNotFoundException(string.Format("Layer with id={0} not found!", layer.Id));
}
vectorLayer.Title = layer.Title;
if (layer.Style != null) layer.Style.SaveStyle(vectorLayer);
vectorLayer.MinScale = layer.MinScale;
vectorLayer.MaxScale = layer.MaxScale;
vectorLayer.GeomType = layer.GeomType ?? "Point";
_context.SaveChanges();
return layer.Id;
}
Any idea why returned Id is always 0?
Your return statement should be vectorLayer.Id.
You are currently returning the Id of the object that was not found in the database and had an Id of 0.
In addition regarding the following code:
vectorLayer.Title = layer.Title;
if (layer.Style != null) layer.Style.SaveStyle(vectorLayer);
vectorLayer.MinScale = layer.MinScale;
vectorLayer.MaxScale = layer.MaxScale;
vectorLayer.GeomType = layer.GeomType ?? "Point";
Consider encapsulating it using a clone like method or a Copy Constructor.
You need to return vectorLayer.Id. You never actually set the layer.Id anywhere. vectorLayer is what you create and add to the DB.
There are several problems with this code.
As everyone else noticed, you are saving vectorLayer, not layer. If you want to return an ID, you should return vectorLayer.Id
Your code returns 0 if the input is missing :
if (layer == null) return 0;
That's not a good idea. It means that you can't differentiate between actual 0s and invalid input. If this is unexpected, throw an exception. If it is, change the method to bool TrySaveVectorLayer(layer,out int id), or (bool ok,int id) SaveVectorLayer(layer)`.
Worst case, return a negative number or some value that's clearly invalid, so you know at least what happened.
It could be something else entirely though, like an ID field that isn't autogenerated, eg through an IDENTITY() or SEQUENCE
return layer.Id; //this id is of wrong object
The above line is returning the ID of the VVectorLayer. But you actually want to return the ID of the inserted data row. That will be the Id in the entity vectorLayer.
So you have to return vectorLayer.Id;
Is this a correct understanding of what this code does - and is it the correct way to update a row which has a URLPath of url so that the IsInProcessing column is true?
I haven't actually tried this code yet. Before I do, I want to try and understand it! It is pieced together from various sources.
The code:
using(var db = new DamoclesEntities())
{
var urls = db.URLS;
var result = urls.FirstOrDefault(u => u.URLPath == url);
result.IsInProcessingQueue = true;
db.SaveChanges();
}
What I think is happening here is within the using I am instantiating the DamoclesEntities() class as var db.
I then instantiate the db.URLS (class / table) to the var urls.
I then find the first row where the URLPath (column) contains url, and that row is assigned to result.
I change that row's IsInProcessingQueue (column value) to true;
Finally, I save the changes to the database.
it is almost correct, but keep in mind, that FirstOrDefault will return null value in case if there is no rows found by specified criteria - URLPath == url.
So in this case next row will produce NullReferenceException.
Just add check of result for a null and do result.IsInProcessingQueue = true;db.SaveChanges(); only if result != null
Using code like this:
AppEntities data = new AppEntities();
var result = data.GIS_CONTRACTOR_TEST.Where(x => x.CONTRACTORNAME == txtSearch.Text);
GridView1.DataSource = result.ToList();
GridView1.DataBind();
I am able to filter data based on the text box. now my question is How I can check if the result is empty or not? I mean if I want to send a message to user that there is not such a value in the database? how can I do that?
Thanks
if (result == null || result.ToList().Count == 0)
{
// Display message
}
You mean outside asking the list whether it has a length of 0? WHich would be the obvious thing to do?
I have a datatable with data in it (customer addresses). In some instances, column ADDR3 doesn't have a value and column ADDR2 does. I'm attempting to check the value of ADDR3 and if it doesn't contain a value I want to copy the value in ADDR2 to ADDR3 and then blank out ADDR2. I was trying to use the below code, but it isn't working. I placed a breakpoint after my 'if' statement, but the program never breaks. But, I know for a fact that a lot of the rows have null ADDR3 fields. Can anyone tell me what I'm doing wrong?
foreach (DataRow row in dataSet11.DataTable1.Rows)
{
object value = row["ADDR3"];
if (value == DBNull.Value)
{
row["ADDR3"] = row["ADDR2"];
row["ADDR2"] = " ";
}
}
It's likely that your row["ADDR3"] value is NEVER equal to DbNull.Value. This is often the case with data tables that were transferred over a web service, for example (there will be empty strings instead of nulls due to the XML transformations).
Put a break point BEFORE your if and find exactly what the value is. You might try checking for row["ADDR3"] == null or string.IsNullOrWhiteSpace(row["ADDR3"].ToString())
Have you tried comparing the value to null (rather than DBNull.Value)? I believe DBNull.Value is exclusive for certain database objects and does not appear once read into a dataset/datatable.
Try this:
foreach (DataRow row in dataSet11.DataTable1.Rows)
{
if (
row.IsNull("ADDR3") // True if the value is null
||
String.IsNullOrWhitespace(row["ADDR3"]) // True if the value is "", " ", etc.
)
{
row["ADDR3"] = row["ADDR2"];
row["ADDR2"] = " ";
}
}
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"