How set XAttribute Value null - linq

XElement xml = new XElement("MyMenu",
from c in db.Security_Module_Menus
//where (c.ParentID == 0)
orderby c.Menu_ID
select new XElement("Item",
new XAttribute("Text", c.Menu_Name), new XAttribute("NavigateUrl", c.Target_URL)
)
);
From my above syntax c.Menu_Name,c.Target_URL values are nullable.Show me the error
Value cannot be null.
Parameter name: value I know SetElementValue() used to solve this error.But how can i use to my above syntax.Help me to Use it.Show me syntax

Presumably you want to avoid creating the attributes if c.Menu_Name and c.Target_URL are null? If so, you can do it as follows:
new XElement("MyMenu",
from c in db.Security_Module_Menus
orderby c.Menu_ID
select new XElement("Item",
c.Menu_Name == null ? null : new XAttribute("Text", c.Menu_Name),
c.Target_URL == null ? null : new XAttribute("NavigateUrl", c.Target_URL))
)

Related

Unable to create a constant value of type 'System.DBNull'. Only primitive types or enumeration types are supported in this context

I try to apply left outer join on the basis of two ids one in the primary key of one table while the foreign key of another table also nullable
var yarnPOFilter_Grid = (from yrq in _context.Yarn_Requisition_Details
//join ypo in
_context.Yarn_PurchaseOrder_Details on yrq.YarnRequsitionDetailID
equals
ypo.YarnRequsitionDetailID into t
join ypo in
_context.Yarn_PurchaseOrder_Details on yrq.YarnRequsitionDetailID
equals
DBNull.Value.Equals(ypo.YarnRequsitionDetailID) ? 0 :
ypo.YarnRequsitionDetailID into t
from rt in t.DefaultIfEmpty() //
DefaultIfEmpty preserves left-hand elements that have no matches on the
right side
select new
{
YarnRequsitionDetailID =
(rt.YarnRequsitionDetailID == null ? long.MinValue :
rt.YarnRequsitionDetailID),
yrq.YarnID,
yrq.Yarn.YarnName,
yrq.YarnFellowID,
yrq.Yarn_FellowCodes.YarnFellowCode,
yrq.QuantityRequired,
rt.QuantityOrdered,
QuantityBalance_Custom =
yrq.QuantityRequired - rt.QuantityOrdered
}).ToList();
return yarnPOFilter_Grid;
I get this error message when I deal with null in joining condition
Unable to create a constant value of type 'System.DBNull'. Only primitive types or enumeration types are supported in this context.
Execute ToList() First before Select as there is no sql equivalent to the conditions you added in the YarnRequsitionDetailID = (rt.YarnRequsitionDetailID == null ? long.MinValue : rt.YarnRequsitionDetailID)
so it will be
from rt in t.DefaultIfEmpty()).ToList().Select(c => new
{
YarnRequsitionDetailID =
(c.rt.YarnRequsitionDetailID == null ? long.MinValue :
c.rt.YarnRequsitionDetailID),
c.yrq.YarnID,
c.yrq.Yarn.YarnName,
c.yrq.YarnFellowID,
c.yrq.Yarn_FellowCodes.YarnFellowCode,
c.yrq.QuantityRequired,
c.rt.QuantityOrdered,
QuantityBalance_Custom =
c.yrq.QuantityRequired - c.rt.QuantityOrdered
}).ToList();
i hope this solved your previous problem

How can I check for null values in this linq query where clause

I have a linq query to locate a matching item in a SharePoint library. It works fine if there is a custom property called 'MMSTerm' but if the property is null then obviously my string modifications will fail and error out when it hits x["MMSTerm"]
I will need to use string.replace in my where operation so a null won't be good.
SPListItem item = (from x in Items.OfType<SPListItem>()
where x["MMSTerm"].ToString() == pageReference.ToString()
select x).ToList<SPListItem>().FirstOrDefault();
Hopefully this is an easy one.
You can verify if field exists with SPFieldCollection.ContainsField method
SPListItem item = (from x in Items.OfType<SPListItem>()
where x.Fields.ContainsField("MMSTerm") &&
(x["MMSTerm"] == null ||
x["MMSTerm"].ToString() == pageReference.ToString())
select x).FirstOrDefault();
Also I think fluent API looks better in this case:
SPListItem item = Items.OfType<SPListItem>()
.FirstOrDefault(x =>
x.Fields.ContainsField("MMSTerm") &&
(x["MMSTerm"] == null ||
x["MMSTerm"].ToString() == pageReference.ToString()));
Since calling x["MMSTerm"] throws an exception when "MMSTerm" does not exist, rather than returning null, you should call ContainsField
x.Fields.ContainsField("MMSTerm")
to see if the field is there:
SPListItem item = (from x in Items.OfType<SPListItem>()
where x.Fields.ContainsField("MMSTerm") && x["MMSTerm"].ToString() == pageReference.ToString()
select x).FirstOrDefault();
Since && short-circuits evaluation when x.Fields.Contains("MMSTerm") is false, the x["MMSTerm"] would not be evaluated.
In case the x["MMSTerm"] could contain nulls, you could use the ""+obj trick to avoid null reference exceptions:
var pageRefStr = pageReference.ToString();
SPListItem item = (from x in Items.OfType<SPListItem>()
where x.Fields.ContainsField("MMSTerm") && pageRefStr.Equals(""+x["MMSTerm"])
select x).FirstOrDefault();

LINQ NullReferenceException on DefaultIfEmpty

I'm looking for a solution to the problem of having the DefaultIfEmpty() extension method not picking up null values when used in a LINQ outer join.
Code as follows:
var SummaryLossesWithNets = (from g in SummaryLosses
join n in nets
on g.Year equals n.Year into grouping
from x in grouping.DefaultIfEmpty()
select new
{
Year = g.Year,
OEPGR = g.OccuranceLoss,
AEPGR = g.AggregateLoss,
OEPNET = ((x.OEPRecovery == null) ? 0 : x.OEPRecovery),
AEPNET = ((x.AEPRecovery == null) ? 0 : x.AEPRecovery),
});
In the List SummaryLosses there are many years worth of data I wish to join to the table 'nets' which contains a sub-portion of the years. The exception is thrown on x being a null value, I am assuming because the years in SummaryLosses not matched by years in nets creates null values in the grouping list.
How should one go about checking for the null value here? As you can see I've attempted to check for null on the properties of x, but since x is null this doesn't work.
Kind regards
Richard
Simply check whether x is null instead:
OEPNET = x == null ? 0 : x.OEPRecovery,
AEPNET = x == null ? 0 : x.AEPRecovery
Or if x.OEPRecovery and x.AEPRecovery are nullable properties too, use:
OEPNET = x == null ? 0 : (x.OEPRecovery ?? 0),
AEPNET = x == null ? 0 : (x.AEPRecovery ?? 0)
If you have many join statements
check check all joined tables and ensure that the foreign key you are using
(in comparing or lets say Interested in) is not null

Linq using nullable datetime field

I have a problem with LINQ (using EF - 4.3.1.0) using the following:
DateTime? dtcollected = DateTime.TryParse(dateCollected, out dateVal) ? dateVal : (DateTime?)null;
DateTime? dtanalyzed = DateTime.TryParse(dateanalyzed, out dateVal) ? dateVal : (DateTime?)null;
var doesexist = (from pw in dbContext.WtTbl
where pw.CompanyId == 13
&& pw.DateCollected == dtcollected
&& pw.DateAnalyzed == dtanalyzed
select pw).Any();
Note that dateCollected came in as a string so I had to convert it to a nullable DateTime. Same goes for dateanalyzed.
What I am struck at is that I have a companyId of 13. A null value of dtcollected. And a value for dtanalyzed already in the table so I would expect doesexist to return true, but it returns false.
If I comment out
var doesexist = (from pw in dbContext.WtTbl
where pw.CompanyId == 13
// && pw.DateCollected == dtcollected
&& pw.DateAnalyzed == dtanalyzed
select pw).Any();
or put:
var doesexist = (from pw in dbContext.WtTbl
where pw.CompanyId == 13
&& pw.DateCollected == null
&& pw.DateAnalyzed == dtanalyzed
select pw).Any();
Then I get a true. How come it is not able to comprehend null value of dtcollected?
Am I doing something wrong.
In most database systems (definitely SQL Server), if one side of the comparison is null, then the result of the comparison is unknown, and therefore not included in the result set (or, for all intents and purposes, false).
That said, you need to perform a check for null against your variables, only checking against the database field if the parameter is non-null, like so:
var doesexist = (
from pw in dbContext.WtTbl
where
pw.CompanyId == 13 &&
(dtcollected == null || pw.DateCollected == dtcollected) &&
(dtanalyzed == null || pw.DateAnalyzed == dtanalyzed)
select pw).Any();
This translates roughly to:
declare #dtcollected date = null
declare #dtanalyzed date = null
select
*
from
Table as t
where
(#dtcollected is null or t.DateCollected = #dtcollected) and
(#dtanalyzed is null or t.DateAnalyzed = #dtanalyzed)

Can't enumerate LinQ results with left join

var itemSet = from item in da.GetList<Models.account>()
join file in objFileStorageList
on item.account_id equals file.parent_id into objFile
from fileItem in objFile.DefaultIfEmpty()
where item.company != null && item.company.company_id == 123
orderby item.updatedDate descending
select
new
{
Id = item.account_id,
RefNo = item.refNo,
StartDate = item.StartDate ,
EndDate = item.EndDate ,
Comment = item.comment,
FileStorageID = fileItem != null ? fileItem.fileStorage_id : -1,
Identification = fileItem != null ? fileItem.identifier : null,
fileName = fileItem != null ? fileItem.file_nm : null
};
It raises error message when I try to enumerate through collection result from Linq query above.
LINQ to Entities does not recognize
the method
'System.Collections.Generic.IEnumerable1[SCEFramework.Models.fileStorage]
DefaultIfEmpty[fileStorage](System.Collections.Generic.IEnumerable1[SCEFramework.Models.fileStorage])'
method, and this method cannot be
translated into a store expression
foreach (var item in itemSet)
{
string itemRef= item.RefNo;
}
Please suggest me any solutions.
Thanks in advance.
I think the problem with this is the following 'from' clause:
from fileItem in objFile.DefaultIfEmpty()
Note that your LINQ query may only be executed at the time the result collection is executed. So while you think your exception is in the foreach, it's actually within your expression. This breaks because the possible null value of objFile.DefaultIfEmpty() cannot cast into an IEnumerable.
Try removing the DefaultIfEmpty call and see what happens.

Resources