I am getting the following error:
Object reference not set to an instance of an object
I don't know what is the cause of this error and how to solve it, here is my code:
while(dr.Read())
{
string variant = dr.GetString(0);
int size = dr.GetInt32(1);
int quantity = dr.GetInt32(2);
DataRow x = dt.Rows
.Cast<DataRow>()
.Where(r => r["variant_name"].Equals(variant) && r["size"].Equals(size))
.FirstOrDefault();
x["quantity"] = quantity;
}
I'm getting the error on this line -> x["quantity"] = quantity;
I'm wondering why it would give a null value because I checked in my database that it should return exactly one match.
FirstOrDefault returns null if the element is not found and you try to access this object.
On the last line x is null, fix with
if(x != null)
x["quantity"] = quantity;
This happens if your condition (.Where) doesn't yield a match.
At that point the FirstOrDefault return the Default part
and this is a null for a reference object as explained in MSDN
The default value for reference and nullable types is null.
while(dr.Read())
{
string variant = dr.GetString(0);
int size = dr.GetInt32(1);
int quantity = dr.GetInt32(2);
DataRow x = dt.Rows
.Cast<DataRow>()
.Where(r => (r["variant_name"].ToString().Equals(variant) && Convert.ToInt32(r["size"]).Equals(size)))
.FirstOrDefault();
if (x != null)
{
x["quantity"] = quantity;
}
}
Thank you for your answer it helped me a lot. I just changed the line .Where a little bit and now it works for me. Thank you again!
Related
This is my current LINQ statement:
var results = from l in leads
select new MyObject
{
LeadID = l.LeadID,
SelectedProposalEngineerID = l.LeadContacts.Where(contact => contact.LeadContactTypeID == LeadContactType.ProposalEngineer).FirstOrDefault().ContactID
};
The trouble I'm having is that the last item is often null. So when I try to convert "results" to a List, I get
{"The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."}
I don't want to make SelectedProposalEngineerID a nullable int, for problems that would cause down stream. How would I give it a value of 0 when it's null?
I have seen a LOT of other threads about this, but I can't seem to adapt any of their answers to this case.
Use DefaultIfEmpty extension method.
var results = from l in leads
select new MyObject
{
LeadID = l.LeadID,
SelectedProposalEngineerID =
l.LeadContacts.Where(contact => contact.LeadContactTypeID == LeadContactType.ProposalEngineer)
.Select(contact => contact.ContactID)
.DefaultIfEmpty(0)
.FirstOrDefault()
};
Nullable<int> ID;
var results = from l in leads
select new MyObject
{
LeadID = l.LeadID,
SelectedProposalEngineerID = (ID = l.LeadContacts.Where(contact => contact.LeadContactTypeID == LeadContactType.ProposalEngineer).FirstOrDefault().ContactID).HasValue ? ID.Value : 0;
};
A ternary operator should do the job. Assign the result to a variable, then if it's not null, cast the variable to int and return it, else return 0.
Sometimes, when I try to lookup insurance name, if it is not found then I want my InsuranceName variable to have null value. But I always get NullReferenceException. I can get around it by putting into series of if statements checking for null, is there anyway to do it in one line?
string InsuranceName = db.Medicares.FirstOrDefault(p => p.MedicareId = 2).Insurances.FirstOrDefault(p => p.InsuranceId = 1).Name;
var medicare = db.Medicares.Include(m => m.Insurances).FirstOrDefault(p => p.MedicareId == 2);
string InsuranceName = medicare == null ? null : medicare.Insurances.FirstOrDefault(p => p.InsuranceId == 1).Name;
I want to check in the below code if no match is found it should not throw object reference null error.
itm.lstCustomziation.AddRange(
(from xx in db.vw_DressingCustomization
where xx.CatID == itm.HeaderName.Value && xx.ProductID == itm.ProductID
select new itmCustomization()
{
catId = (int)xx.CatID,
custType = customizationType.Dressing,
isCustomziationDisplay = xx.IsDefaultDisplay,
isFixLimit = (bool)xx.isDefaultLimit,
maxLimit = (short)xx.DefaultFreeCount,
itmName = xx.Description,
isItemDefault = xx.IsDefaultDisplay,
price = (double)xx.MainPrice,
proId = (int)xx.ProductID
}).ToList<itmCustomization>());
You should break it into multiple steps. First execute the query and get the results. Then you should check for null/count and based on that check call the add range method. It would be more readable as well.
Add check whether your nullable itm.HeaderName really has value before accessing that value:
where itm.HeaderName.HasValue && // check if value exists
xx.CatID == itm.HeaderName.Value && // otherwise here is the problem
xx.ProductID == itm.ProductID
I am using the below code and trying to group by Currency and Code. After this I am trying to loop through the result set.
But the issue is while looping through the results, at the end I am getting the below exception on the for each statement:
Object cannot be cast from DBNull to other types.
DataTable dt = new DataTable();
var result = from r in dt.AsEnumerable()
result r by new
{
currency = r.Field<String>("CURRENCY"),
Code = r.Field<String>("CODE")
}
into grp
select new
{
currency = grp.Key.currency,
Code = grp.Key.Code,
amount = grp.Sum(x => Convert.ToDouble(x["AMOUNT"]))
};
foreach (var obj in result)
{
String sCurr =obj.currency;
String Code = obj.Code;
string amount= obj.amount.ToString());
}
Please help me to resolve this issue.
Something like
amount = grp.Sum(x => Convert.ToDouble(x["AMOUNT"] == DBNull.Value ? 0 : x["AMOUNT"]));
If that is the line that is giving you the problem.
The way to find the number of CELLS with DBNulls for a specific column:
int numOfEmptyColA = MyDataTable.AsEnumerable().Where(p=>p.IsNull("ColA")).Count();
This:
amount = grp.Sum(x => Convert.ToDouble(x["AMOUNT"]))
will not work as you expect. If x["AMOUNT"] is DBNull.Value instead of a valid double, the conversion will fail with an exception. Instead, try:
amount = grp.Sum(x.Field<double?>("AMOUNT"))
if you expect that field to be a double. Sum will treat the null values as zero, per MSDN.
I'm not sure which one is getting the error, but you can can compare it to DBNull.Value like so.
String sCurr = obj.currency == DBNull.Value ? "" : obj.currency;
I have a problem with making WHERE clause with LINQ. I tried to google it but I've only got answers on what to do if the external variable is the type of nullable integer... well, I've tried these methods the other way around (I have 0...1 relations in my dataset):
e.g.
int oldId = oldQuestion.id;
IEnumerable<possible_answer> possibleAnswersQuery =
from x in Mentor11Entities.possible_answers
where object.Equals(x.question_id, oldId)
select x;
List<possible_answer> possibleAnswers =
possibleAnswersQuery.ToList<possible_answer>();
or
int oldId = oldQuestion.id;
IEnumerable<possible_answer> possibleAnswersQuery =
from x in Mentor11Entities.possible_answers
where Convert.ToInt32(x.question_id ?? 0).Equals(oldId)
select x;
List<possible_answer> possibleAnswers =
possibleAnswersQuery.ToList<possible_answer>();
but I'm always getting the error that LINQ doesn't support certain functions... is there any way to get around the problem?
just use
where x.question_id != null && x.question_id == oldId
so your query should be:
IEnumerable<possible_answer> possibleAnswersQuery =
from x in Mentor11Entities.possible_answers
where x.question_id != null && x.question_id == oldId
select x;