在Lambda表达式中的空值 – Entity Framework

huangapple go评论132阅读模式
英文:

Null value in lambda expression - Entity Framework

问题

我需要获取OrgName的值(它可能是空值)。

问题出在我的Lambda表达式中,因为c.Organization也可能是空的。如果它是空的,我会得到一个错误。你有任何想法,如何解决这个问题?谢谢

var users = _userManager.Users.Select(c => new UsersViewModel()
{
    Id = c.Id,
    Username = c.UserName,
    Email = c.Email,
    Role = string.Join(",", _userManager.GetRolesAsync(c).Result.ToArray()),
    OrgName = _db.Organizace.FirstOrDefault(a => a.Id == c.Organization)?.OrgName.ToString()
}).ToList();
英文:

I need to get value for OrgName (it could be null value).

Problem is in my lambda expression, because c.Organization could be null as well. And if is null, I get an error. Do you have any idea, how can I accomplish this issue? Thanks

var users = _userManager.Users.Select(c => new UsersViewModel()
        {
            Id = c.Id,
            Username = c.UserName,
            Email = c.Email,
            Role = string.Join(",", _userManager.GetRolesAsync(c).Result.ToArray()),
            OrgName = _db.Organizace.FirstOrDefault(a => a.Id == c.Organization).OrgName.ToString()
        }).ToList();

答案1

得分: 2

你可以使用空条件运算符:

OrgName = _db.Organizace.FirstOrDefault(a => a.Id == c.Organization)?.OrgName;

然而,你目前的做法非常低效,会导致大量的数据库调用。

你应该考虑使用导航属性包含来以更高效的方式实现相同的行为。

英文:

You can use null conditional operators:

OrgName = _db.Organizace.FirstOrDefault(a => a.Id == c.Organization)?.OrgName;

However, what you are doing is very inefficient and will result in many database calls.

You should explore using navigation properties and includes instead to achieve the same behaviour in a more efficient manner.

答案2

得分: 1

我会在 lambda 内部检查是否为 null。

var users = _userManager.Users.Select(c => new UsersViewModel()
{
    Id= c.Id,
    Username = c.UserName,
    Email = c.Email,
    Role = string.Join(",", _userManager.GetRolesAsync(c).Result.ToArray()),
    OrgName = c.Organization != null ? _db.Organizace.FirstOrDefault(a => a.Id == c.Organization).OrgName.ToString() : string.Empty
}).ToList();
英文:

I would check for null inside the lambda.

var users = _userManager.Users.Select(c => new UsersViewModel()
{
    Id= c.Id,
    Username = c.UserName,
    Email = c.Email,
    Role = string.Join(",", _userManager.GetRolesAsync(c).Result.ToArray()),
    OrgName = c.Organization != null ? _db.Organizace.FirstOrDefault(a => a.Id == c.Organization).OrgName.ToString() : string.Empty
}).ToList();

答案3

得分: 0

OrgName = _db.Organizace.FirstOrDefault(a => a.Id == c.Organization)?.OrgName

英文:

Try this

OrgName = _db.Organizace.FirstOrDefault(a => a.Id == c.Organization)?.OrgName

huangapple
  • 本文由 发表于 2023年3月10日 00:33:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定