Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

c# - How to get data from child to parent entity framework core?

I have two table like this -

public class Job
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime AddedTime { get; set; } = DateTime.Now;
    public DateTime LastEdit { get; set; } = DateTime.Now;
    public string  Explanation { get; set; }
    public string PhotoString { get; set; }

    public bool isActive { get; set; } = true;

    public int CompanyId { get; set; }
    public Company Company { get; set; }
}

and company -

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Explanation { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string PhotoString { get; set; }

    public bool isActive { get; set; } = true;

    public int AppUserId { get; set; }
    public AppUser AppUser { get; set; }
    public List<Job> Jobs { get; set; }
}

I only want to get AppUserId from Company and all Jobs from every Company. I tried this and it gave me error.

using var context = new SocialWorldDbContext();
return await context.Jobs.Where(I => I.isActive == true && I.Company.isActive).Include(I=>I.Company.AppUserId).ToListAsync();

So my question is there any way I can get this data from parent?

question from:https://stackoverflow.com/questions/65938511/how-to-get-data-from-child-to-parent-entity-framework-core

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Include adds whole entities to the output. To add just one property use Select, something like

 context.Jobs
        .Where(I => I.isActive == true && I.Company.isActive)
        .Select(e => new {Job=e, CompanyAppUserId = e.Company.AppUserId})
        .ToListAsync();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...