How to use efcore get value but may be null?

mc 3,681 Reputation points
2022-08-09T05:53:57.443+00:00

There is 2 tables:

A:

public int Id{get;set;}  
public int CreatorId{get;set;}  

B:

public int Id{get;set;}  
public string Name{get;set;}  

I want to get the Name in B according the CreatorId in A but the CreatorId may not in B then I want it to be null.

I know you may say I can do this:

from a in _context.A  
from b in _context.B  
where a.CreatorId = b .Id  
select new {  
a.Id  
b.Name  
}  

But If the CreatorId is not in B there will be no record I want the Name be null.
how to do it?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 24,286 Reputation points Microsoft Vendor
    2022-08-10T02:33:46.06+00:00

    @mc , Welcome to Microsoft Q&A, based on my further test and research, I find that It is hard for us to use One linq query to get what you wanted.

    As you mentioned, we need to consider alone the situation about If the CreatorId is not in B there will be no record I want the Name be null .

    Here is a code example you could refer to.

    code.txt

    Database and Result:

    229716-image.png

    229783-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.