英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论