It's a WINDOWSFORM
I have combobox, I use this code for auto textboxvalue but I receive this error
Sequence contains no elements
private void cmbOfficeNumber_SelectedIndexChanged(object sender, EventArgs e)
{
using (UnitOfWork db = new UnitOfWork())
if (cmbOfficeNumber.SelectedValue.ToString() != null)
{
txtOfficeName.Text = db.OfficeRepository.GetOfficeNamebyNumber(cmbOfficeNumber.Text);
}
}
And this is my repository code
public string GetOfficeNamebyNumber(string officeNumber)
{
return db.Office.First(g => g.OfficeNumber == officeNumber).OfficeName;
}
EDIT: When using
return db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber).OfficeName;
I receive a different error
Object reference not set to an instance of an object
If First() results in
Sequence contains no elements
That means the condition in the lambda expression resulted in no hits. Because First requires you to have atleast one match.
If FirstOrDefault().Property results in
Object reference not set to an instance of an object
It means that the lambda expression resulted in no hits, and it returns a default value of the return type. In the case of a reference object it will be null. You then tried to access a property of null which causes the exception.
Simply put. Your problem is that your comparison is returning no hits.
You need to insert a fail safe for this to not crash
Something like:
public string GetOfficeNamebyNumber(string officeNumber)
{
var result = db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber);
if(result == null)
return string.Empty;
return result.OfficeName;
}
This can also be shortend to
public string GetOfficeNamebyNumber(string officeNumber)
{
var result = db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber);
return result?.OfficeName ?? string.Empty;
}
Or even
public string GetOfficeNamebyNumber(string officeNumber)
{
return db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber)?.OfficeName ?? string.Empty;
}
I hope this step by step explanation gives you the information you need to solve the problem.
Related
I want to check if the email that user entered already exist in Office table,take a look bellow what I have done so far, the problem is that officeEmail is always true, even though the entered email doesn't exist it's never returning NULL.
public static bool IsOfficeEmail(string email)
{
using (var data = Database)
{
data.ObjectTrackingEnabled = false;
var officeEmail = data.Offices.Where(a => a.Active && a.Email.Equals(email));
if (officeEmail != null)
return true;
}
return false;
}
Where will not return you null, but empty sequence, change it to:
var officeEmail = data.Offices.FirstOrDefault(a => a.Active && a.Email.Equals(email));
if (officeEmail != null)
return true;
FirstOrDefault will return default value (here null) it will not find queried value.
It is an option to use Any if you are not interested in email record:
public static bool IsOfficeEmail(string email)
{
using (var data = Database)
{
return data.Offices.Any(a => a.Active && a.Email.Equals(email))
}
}
You will not get email record if you will not use it anyway. Which approach you should use depends on what will you do with officeEmail, if you are just querying if it exists -> Any will be the best approach here. If you would like to get check for existing record and do something with it, FirstOrDefault will be better.
Alternativly if you really want to use .Where you can also check if the returned collection contains ANY elements:
if (officeMail.Any()) // ...
Or even shorter:
if (officeMail.Any(a => a.Active && a.Email.Equals(email))) // ...
If you want to ensure that there is exactly ONE item within your list matching your condition use .Single instead of .Any which will throw an exception if none or more then one item was found.
The actual reason for your check allways returning true is that .Where will return an enumerator even when no item matches the condition. Therefor the result is never null.
I'm looping through a property on a dynamic object looking for a field, except I can't figure out how to safely evaluate if it exists or not without throwing an exception.
foreach (dynamic item in routes_list["mychoices"])
{
// these fields may or may not exist
int strProductId = item["selectedProductId"];
string strProductId = item["selectedProductCode"];
}
using reflection is better than try-catch, so this is the function i use :
public static bool doesPropertyExist(dynamic obj, string property)
{
return ((Type)obj.GetType()).GetProperties().Where(p => p.Name.Equals(property)).Any();
}
then..
if (doesPropertyExist(myDynamicObject, "myProperty")){
// ...
}
This is gonna be simple. Set a condition which checks the value is null or empty. If the value is present, then assign the value to the respective datatype.
foreach (dynamic item in routes_list["mychoices"])
{
// these fields may or may not exist
if (item["selectedProductId"] != "")
{
int strProductId = item["selectedProductId"];
}
if (item["selectedProductCode"] != null && item["selectedProductCode"] != "")
{
string strProductId = item["selectedProductCode"];
}
}
You need to surround your dynamic variable with a try catch, nothing else is the better way in makking it safe.
try
{
dynamic testData = ReturnDynamic();
var name = testData.Name;
// do more stuff
}
catch (RuntimeBinderException)
{
// MyProperty doesn't exist
}
In IEnumerable.First function, how do I handle the case if there are no matches? Currently it just crashes...
MySPListItem firstItem = itemCollection.First(item => !item.isFolder);
if (firstItem != null)
{
TreeNode firstNode = GetNodeByListItem(my_treeview.Nodes, firstItem, ReportObject);
if (firstNode != null)
{
ReportObject.log("Selecting the first PDF");
selectPDF(my_treeview, firstNode, queryStr_param);
}
}
Error Message:
Sequence contains no matching element
Stacktrace: at System.Linq.Enumerable.First[TSource](IEnumerable1 source, Func2
predicate)
Ok, If it is exceptional for there to be no first,
try
{
var first = enumerable.First();
}
catch (InvalidOperationException)
{
// Oops, that was exceptional.
}
If you anticipate that there may be no first in some valid situations,
var first = enumerable.FirstOrDefault();
if (first == default(someType)) // null for reference types.
{
// Ok, I need to deal with that.
}
While you do a null check on the find, you don't in your predicate. The line
foundItem = itemCollection.Find(item => item.item.ID == PDFID);
Might throw an exception it item is null (have you inserted an null item in the collection?) or item.item is null (are you sure it's always there?).
You could do:
foundItem = itemCollection.Find(item => item != null &&
item.item != null &&
item.item.ID == PDFID);
More chatty, but you won't get a NullReferenceException.
Edit Well you changed your question. Now you do First. The First method will throw an exception if nothing is found. Use FirstOrDefault instead which will return null for a class or the default value for a struct.
foundItem = itemCollection.FirstOrDefault(item => item != null &&
item.item != null &&
item.item.ID == PDFID);
Replace First by FirstOrDefault :
MySPListItem firstItem = itemCollection.FirstOrDefault(item => !item.isFolder);
Quoted from the MSDN website you linked to:
The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.
This describes the return value. Hence, when no match is found, the default value for type T is returned, which means null for reference types, and things such as 0, false & co. for value types.
So in your calling code, simply check for this default value, and you're fine :-). What you can not do is just use the value that is being returned, as this e.g. might result in a NullReferenceException, if you are using a reference type.
Check if the result is null:
if (result == null)
{
Console.WriteLine("Not found");
}
There is a clear example demonstrating what to do if the item is found/not found here
It shouldn't throw an exception, you need to handle the case where it returns default(T). You might be getting a NullReferenceException because you're not handling the case where it returns null. For example:
IEnumerable<Cars> cars = GetCars();
Car car = cars.Find(c => c.Model == "Astra");
if(car != null)
{
// You found a car!
}
If you were doing the same for a struct, you'd check for it's default instead. Ints for example would be a 0:
int[] ints = new int[] { 1, 4, 7 };
int myInt = ints.Find(i => i > 5);
if(myInt != 0) // 0 is default(int)
{
// You found a number
}
I already use linq but search id only and it worked perfectly
var obj = (from VAR in db.infos
where VAR.id == 22
select new
{
title = VAR.title,
}).SingleOrDefault();
Label2.Text = obj.title.Trim();
If I try to search by location get a error
var obj = (from VAR in db.infos
where VAR.location.Trim() == "Lim"
select new
{
title = VAR.title.Trim(),
}).SingleOrDefault();
SearchJob.Items.Add(obj.title.Trim());
Label2.Text = obj.title;
Have a error in label2 line
Object reference not set to an instance of an object.
How do I fix it?
if (obj.title != null)
{
SearchJob.Items.Add(obj.title.Trim());
Label2.Text = obj.title;
}
Object reference not set to an instance of an object.
SOLUTION
Change SingleOrDefault() to FirstOrDefault()
You're doing some nasty stuff there, VERY bad habits. For instance this:
var obj = (from VAR in db.infos
where VAR.location.Trim() == "Lim"
select new
{
title = VAR.title.Trim(),
}).SingleOrDefault();
SearchJob.Items.Add(obj.title.Trim());
Label2.Text = obj.title;
Is a nonsense! Let me tell you why:
Always check the data BEFORE you insert it into your database, not AFTER. You're creating a lot of unnecessary overhead this way, which could be avoided altogether. Trim the data before, never after.
Next thing - you need only a single string value, yet you create an anonymous object. WHY? Do this instead:
string title = (from o in db.infos
where o.location == "Lim"
select o.title).SingleOrDefault();
Use SingleOrDefault if you expect a single result or none. However, if you expect multiple results and want only the first, use FirstOrDefault.
As you can see, I'm using o instead of VAR. It's true it doesn't really matter that much, BUT, it's never a good idea to use a word that's very similar to one of the reserved words (var).
If you get an exception Object reference not set to an instance of an object., it means that your query returned a null and you're trying to access a non-existing object. If your query may return null at some point, always check for null when accessing a member!
EDIT
if ( obj.title != null )
is bad too, because you need to check for null the object itself!
if (obj != null)
if you really want to use your bad approach.
I think the error occurred in the query
In first query you have source db.infos
In second you have source db.jobinfos
The source is changed
If we assign empty text to Label it will show, It looks like that obj.title does not exist or you are getting error in your query due to wrong source.
The obj is not returning title field. Check obj by debugging.
Try to skip exception :)
public static class LINQException {
public static void TryExample() {
var LsWithEx = from p in Enumerable.Range(0, 10) select int.Parse("dsfksdj");
var LsSkipEx = (from p in Enumerable.Range(0, 10) select int.Parse("dsfksdj")).SkipExceptions();
}
public static IEnumerable<T> SkipExceptions<T>(this IEnumerable<T> values)
{
using (var enumerator = values.GetEnumerator())
{
bool next = true;
while (next)
{
try
{ next = enumerator.MoveNext();}
catch
{ continue;}
if (next) yield return enumerator.Current;
}
}
}
}
var obj = (from VAR in db.infos
where VAR.location.Trim() == "Lim"
select new
{
title = VAR.title.Trim(),
}).SkipExce.SingleOrDefault();
I am having this Linq To SQL query which is taking Customer Category from database.The CustCategory will be defined already.Here is the query.
public IList<string> GetAccountType()
{
using (var db = new DataClasses1DataContext())
{
var acctype = db.mem_types.Select(account=>account.CustCategory).Distinct().ToList();
if (acctype != null)
{
return acctype;
}
}
}
Currently I am getting an error that Not all code paths return a value.If I am always certain that the value is there in the database then do I need to check for null,If I need to check for null then how do I handle this.
Can anyone help me with this.
Any suggestions are welcome.
Since Enumerable.ToList never returns null (see the Return Value section of the documentation), you can safely remove the if.
EDIT: Note that, no matter what your database contains, acctype will never be null:
If no value is found in the database, the return value will be an empty list (which is different than null).
If one record is found and its value is null, the return value will be a valid list with one entry, whose value is null. Still, the list itself is not null.
What happens if:
if (acctype != null)
Is null? What is your method supposed to return?
You need to return something
This is not about LINQ to SQL, the method GetAccountType() must return IList<string>. You should return return acctype; and then check this returned list later using Any(), something like:
if(GetAccountType.Any()){
//not empty
}
How about something like this for a fairly clean and readable solution?:
(Note, updated: removed the check for null, since it would clearly not have any effect).
public IList<string> GetAccountType()
{
var acctype = new List<string>();
using (var db = new DataClasses1DataContext())
{
acctype = db.mem_types.Select(
account=>account.CustCategory).Distinct().ToList();
}
return acctype;
}
You need to return a value from your function:
public IList<string> GetAccountType()
{
using (var db = new DataClasses1DataContext())
{
var acctype = db.mem_types.Select(account=>account.CustCategory).Distinct().ToList();
if (acctype != null)
{
return acctype;
}
}
return acctype;
}