简体   繁体   中英

I want to bring data from multiple tables with entityframework using linq method in dotnetcore web api controller

public class Mission
    {
        public int Id { get; set; }        
        public string Name { get; set; }        
        public long Duration { get; set; }// time stored in second        
        public string Aircraft { get; set; }
        public string Syllabus { get; set; }        
        public int MissionTypeId { get; set; }
        public int PhaseId { get; set; }        
        public MissionType Type { get; set; }        
        public  Phase Phase { get; set; }
    }

public class Phase
    {        
        public int PhaseId { get; set; }
        public string PhaseName { get; set; }
        public  ICollection<Mission> Missions { get; set; }

    }
public class MissionType
    {
        public int MissionTypeId { get; set; }
        public string MissionTypeName { get; set; }
        
        public  ICollection<Mission> Missions { get; set; }


    }

// When I am using await context.Missions.ToListAsync(); in controller it is giving me list of items like this format.

    "id": 1,
    "name": "ID-1",
    "duration": 3600,
    "aircraft": "PT-6",
    "syllabus": "BASIC CONV",
    "missionTypeId": 1,
    "phaseId": 1,
    "type": null,
    "phase": null
}

// I need the list in this format. Which linq query method i can use to get a result from the database like this

    {
        "id": 1,
        "name": "ID-1",
        "duration": 3600,
        "aircraft": "PT-6",
        "syllabus": "BASIC CONV",
        "missionTypeId": 1,
        "phaseId": 1,
        "type": {
            "missionTypeId": 1,
            "missionTypeName": "ID - 1 "
        },
        "phase": {
            "phaseId": 1,
            "phaseName": "ID"
        }
    }

Try below codes:

var mission = (from m in _context.Missions
                join t in _context.MissionTypes on m.MissionTypeId equals t.MissionTypeId
                join p in _context.Phases on m.PhaseId equals p.PhaseId
                select new Mission
                {
                    Id = m.Id,
                    Name = m.Name,
                    Duration = m.Duration,
                    Aircraft = m.Aircraft,
                    Syllabus = m.Syllabus,
                    MissionTypeId = m.MissionTypeId,
                    PhaseId = m.PhaseId,
                    Type = m.Type,
                    Phase = m.Phase
                }).FirstOrDefault();

You need to explicitly tell EF Core which related entities you want to load.

Try this:

await context.Missions
    .Include(m => m.Type)
    .Include(m => m.Phase)
    .ToListAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM