开发者

how can I use FirstOrDefault()?

开发者 https://www.devze.com 2023-02-01 01:51 出处:网络
I have this code and I want to set a value to Viewdate when the expression returns no data: ViewData[\"Fix\"] = db.PreStatusViws.Where(c => c.LkpNameFix == \"1\").FirstOrDefault().NumCoefficientFi

I have this code and I want to set a value to Viewdate when the expression returns no data:

ViewData["Fix"] = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault().NumCoefficientFix;

can I set zero or a "Text" for that? I no, what can I do?! note: FirstOrDefault(null) caus开发者_开发问答e an error.


If I understand your question correctly, the following code should solve your problem:

var p = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault(); 
if(p != null)
    ViewData["Fix"] = p.NumCoefficientFix;
else
    ViewData["Fix"] = 0;


Default will return the default for the data type. If the data type in that place is a reference type (e.g. string) the default value will always be null, and therefore the following .NumsCoefficientFix member will throw a NullReferenceException.

The default value is built into .NET and not changeable, and is always given if the result set contains no value.

@Mikey has already given the code sample in his answer that I would suggest.


If you first select the numeric column, FirstOrDefault will work as you intend, returning either a value or 0 (the default for numeric types):

ViewData["Fix"] = db.PreStatus
  .Select (c => c.NumCoefficientFix)
  .FirstOrDefault (c => c.LkpNameFox == "1");

If NumCoefficientFix is a nullable type, then use the ?? operator to convert the null into 0:

ViewData["Fix"] = db.PreStatus
  .Select (c => c.NumCoefficientFix)
  .FirstOrDefault (c => c.LkpNameFox == "1") ?? 0;

Selecting the NumCoefficientFix first is also (slightly) more efficient for LINQ-to-database queries, in that the SQL generated will select only that column.


You just have to select your NumCoefficientFix property before calling FirstOrDefault:

ViewData["Fix"] = db.PreStatusViws
                    .Where(c => c.LkpNameFix == "1")
                    .Select(c => c.NumCoefficientFix)
                    .FirstOrDefault();`

Or in LINQ notation:

ViewData["Fix"] = (from c in db.PreStatusViws
                   where c.LkpNameFix == "1"
                   select c.NumCoefficientFix
                  ).FirstOrDefault();
0

精彩评论

暂无评论...
验证码 换一张
取 消