none
EF Linq how to use same class when use new select RRS feed

  • Question

  • see my example 

        public class MenuItem
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int ParentId { get; set; }
            public virtual ICollection<MenuItem> Children { get; set; }
        }


                List<MenuItem> allMenu = new List<MenuItem>
                {
                    new MenuItem {Id=1,Name="Parent 1", ParentId=0},
                    new MenuItem {Id=2,Name="child 1", ParentId=1},
                    new MenuItem {Id=3,Name="child 2", ParentId=1},
                    new MenuItem {Id=4,Name="child 3", ParentId=1},
                    new MenuItem {Id=5,Name="Parent 2", ParentId=0},
                    new MenuItem {Id=6,Name="child 4", ParentId=4}
                };
    
    
                List<MenuDTO> query = allMenu.Where(i => i.ParentId == 0)
                    .Select(e => new MenuItem
                    {
                        Id = e.Id,
                        Name = e.Name,
                        ParentId = e.ParentId,
                        Children = allMenu.Where(x => x.ParentId == e.Id).ToList()
                    }).ToList();
    

    this line giving error .Select(e => new MenuItem

    so tell me how could i use the same class instead of creating new class.

    for the time being i create a new class called MenuDTO which look same as MenuItem and then i could use that MenuDTO in select

    here is the code

        public class MenuDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int ParentId { get; set; }
            public virtual ICollection<MenuItem> Children { get; set; }
        }

                List<MenuItem> allMenu = new List<MenuItem>
                {
                    new MenuItem {Id=1,Name="Parent 1", ParentId=0},
                    new MenuItem {Id=2,Name="child 1", ParentId=1},
                    new MenuItem {Id=3,Name="child 2", ParentId=1},
                    new MenuItem {Id=4,Name="child 3", ParentId=1},
                    new MenuItem {Id=5,Name="Parent 2", ParentId=0},
                    new MenuItem {Id=6,Name="child 4", ParentId=4}
                };
    
    
                List<MenuDTO> query = allMenu.Where(i => i.ParentId == 0)
                    .Select(e => new MenuDTO
                    {
                        Id = e.Id,
                        Name = e.Name,
                        ParentId = e.ParentId,
                        Children = allMenu.Where(x => x.ParentId == e.Id).ToList()
                    }).ToList();

    now code is working but i have to create new class to use for select.

    is there any way which enable me to use same class instead of creating new dto class.

    help me with sample example if possible. thanks

    Friday, March 16, 2018 2:29 PM

Answers

  • Hi Sudip_inn,

    >>when i am querying mentuitem then i can not use menuitem to populate. how to make it possible without dto used? share idea please.

    According to your description and related code. I create a simple console app, it works. code below for your reference.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApp6
    {
        public class MenuItem
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int ParentId { get; set; }
            public virtual ICollection<MenuItem> Children { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                List<MenuItem> allMenu = new List<MenuItem>
                {
                    new MenuItem {Id=1,Name="Parent 1", ParentId=0},
                    new MenuItem {Id=2,Name="child 1", ParentId=1},
                    new MenuItem {Id=3,Name="child 2", ParentId=1},
                    new MenuItem {Id=4,Name="child 3", ParentId=1},
                    new MenuItem {Id=5,Name="Parent 2", ParentId=0},
                    new MenuItem {Id=6,Name="child 4", ParentId=4}
                };
    
    
                List<MenuItem> query = allMenu.Where(i => i.ParentId == 0)
                    .Select(e => new MenuItem
                    {
                        Id = e.Id,
                        Name = e.Name,
                        ParentId = e.ParentId,
                        Children = allMenu.Where(x => x.ParentId == e.Id).ToList()
                    }).ToList();
    
                foreach (var item in query)
                {
                    Console.WriteLine("{0}  ---  {1} --- {2}", item.Id, item.Name, item.ParentId);
                }
                Console.ReadLine();
            }
        }
    }
       

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Sudip_inn Thursday, March 22, 2018 12:13 PM
    Monday, March 19, 2018 1:49 AM
    Moderator

All replies

  • All the DTO(s) can be kept in a classlib project called Entities. So, all the other projects set project reference to Entities and know what the DTO(s) are about with the DTO(s) being in one spot and not a bunch of classes holding data all over the place like breading rabbits.

     BTW, all collections and arrays have a plural naming convention. allMenu should be called menuitems.

    On that same note, any DTO that is has another class within the DTO, that class should have a DTO name , like MenuItemDTO

    public class MenuDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int ParentId { get; set; }
            public virtual ICollection<MenuItem> MenuItems { get; set; }
        }

    Example usage of the DTO being used in other projects and Entities project is being referenced.

    using System;
    
    namespace Entities
    {
        public class DtoTask
        {
            public int TaskId { get; set; }
            public string TaskName { get; set; }
            public string Note { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime? EndDate { get; set; }
            public string ResourceId { get; set; }
            public int ProjectId { get; set; }
            public string TaskDuration { get; set; }
            public string TaskSpent { get; set; }
            public string Status { get; set; }
        }
    }
    
    ----------------------------------------------
    
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using DAL.Model;
    using Entities;
    
    namespace DAL
    {
        public class DaoTask :IDaoTask
        {
            public DtoTask GetTaskById(int id)
            {
                var dto = new DtoTask();
    
                using (var context = new ProjectMgmntEntities())
                {
                    var task = (context.Tasks.Where(a => a.TaskId == id)).SingleOrDefault();
    
                    if (task == null) return dto;
                    dto.TaskId = task.TaskId;
                    dto.TaskName = task.TaskName;
                    dto.Note = task.Note;
                    dto.StartDate = task.StartDate;
                    dto.EndDate = task.EndDate;
                    dto.ResourceId = task.ResourceId;
                    dto.ProjectId = (int) task.ProjectId;
                    dto.TaskDuration = task.TaskDuration;
                    dto.TaskSpent = task.TaskSpent;
                    dto.Status = task.Status;
                }
    
                return dto;
            }
    
            public List<DtoTask> GetTasksByProjectId(int id)
            {
                var dtos = new List<DtoTask>();
    
                using (var context = new ProjectMgmntEntities())
                {
                    var tasks = (from a in context.Tasks select a);
    
                    foreach (var task in tasks)
                    {
                        if (task.ProjectId != id) continue;
    
                        var dto = new DtoTask
                        {
                            TaskId = task.TaskId,
                            TaskName = task.TaskName,
                            Note = task.Note,
                            StartDate = task.StartDate,
                            EndDate = task.EndDate,
                            ResourceId = task.ResourceId,
                            ProjectId = (int) task.ProjectId,
                            TaskDuration = task.TaskDuration,
                            TaskSpent = task.TaskSpent,
                            Status = task.Status
                        };
    
                        dtos.Add(dto);
                    }
                   
                }
    
                return dtos;
            }
    
            public void CreateTask(DtoTask dto)
            {
                using (var context = new ProjectMgmntEntities())
                {
                    var task = new Task
                    {
                        TaskId = dto.TaskId,
                        TaskName = dto.TaskName,
                        Note = dto.Note,
                        StartDate = dto.StartDate,
                        EndDate = dto.EndDate,
                        ResourceId = dto.ResourceId,
                        ProjectId = dto.ProjectId,
                        TaskDuration = dto.TaskDuration,
                        TaskSpent = dto.TaskSpent,
                        Status = dto.Status
                    };
    
                    context.Tasks.Add(task);
                    context.SaveChanges();
                }
            }
    
            public void UpdateTask(DtoTask dto)
            {
                var task = new Task();
    
                using (var context = new ProjectMgmntEntities())
                {
                    task = (context.Tasks.Where(a => a.TaskId == dto.TaskId)).SingleOrDefault();
                }
    
                if (task != null)
                {
                    task.TaskId = dto.TaskId;
                    task.TaskName = dto.TaskName;
                    task.Note = dto.Note;
                    task.StartDate = dto.StartDate;
                    task.EndDate = dto.EndDate;
                    task.ResourceId = dto.ResourceId;
                    task.ProjectId = dto.ProjectId;
                    task.TaskDuration = dto.TaskDuration;
                    task.TaskSpent = dto.TaskSpent;
                    task.Status = dto.Status;
                }
    
                using (var dbcontext = new ProjectMgmntEntities())
                {
                    if (task == null) return;
                    dbcontext.Entry(task).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
    
            public void DeleteTask(int id)
            {
                Task task;
    
                using (var context = new ProjectMgmntEntities())
                {
                    task = (context.Tasks.Where(a => a.TaskId == id)).SingleOrDefault();
                }
    
                using (var newContext = new ProjectMgmntEntities())
                {
                    newContext.Entry(task).State = EntityState.Deleted;
                    newContext.SaveChanges();
                }
            }
        }
    }
    
    --------------------------------------------------
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using DAL;
    using Entities;
    
    namespace MVC.Models
    {
        public class TaskModels :ITaskModels
        {
            public TaskViewModels GetTasksByProjectId(int id)
            {
                var vm = new TaskViewModels { Tasks = new List<TaskViewModels.TaskEdit>() };
    
                var dtos = new DaoTask().GetTasksByProjectId(id);
    
                vm.Tasks.AddRange(dtos.Select(task => new TaskViewModels.TaskEdit
                {
                    TaskId = task.TaskId,
                    TaskName = task.TaskName,
                    Note = task.Note,
                    StartDate = task.StartDate,
                    EndDate = task.EndDate,
                    ResourceId = task.ResourceId,
                    ProjectId = task.ProjectId,
                    TaskDuration = task.TaskDuration,
                    Status = task.Status
                }).ToList());
    
                return vm;
            }
    
            public TaskViewModels.TaskCreate Create()
            {
                var task = new TaskViewModels.TaskCreate();
                
                return (TaskViewModels.TaskCreate)PopulateDropDownLists(task, "Create");
            }
    
            public void Create(TaskViewModels.TaskCreate task, int id)
            {
                var dto = new DtoTask
                {
                    TaskId = task.TaskId,
                    TaskName = task.TaskName,
                    Note = task.Note,
                    StartDate = (DateTime) task.StartDate,
                  //  EndDate = (DateTime) task.EndDate,
                    ResourceId = task.ResourceId,
                    ProjectId = id,
                    TaskDuration = task.TaskDuration,
                    Status = task.Status
                };
    
                new DaoTask().CreateTask(dto);
            }
    
            public TaskViewModels.TaskEdit Edit(int id)
            {
                var dto = new DaoTask().GetTaskById(id);
    
                var task = new TaskViewModels.TaskEdit()
                {
                    TaskId = dto.TaskId,
                    TaskName = dto.TaskName,
                    Note = dto.Note,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    ResourceId = dto.ResourceId,
                    ProjectId = dto.ProjectId,
                    TaskDuration = dto.TaskDuration,
                    TaskSpent = dto.TaskSpent,
                    Status = dto.Status
                };
    
                return (TaskViewModels.TaskEdit)PopulateDropDownLists(task, "Edit");
            }
    
            public void Edit(TaskViewModels.TaskEdit task)
            {
                var dto = new DtoTask
                {
                    TaskId = task.TaskId,
                    TaskName = task.TaskName,
                    Note = task.Note,
                    StartDate = (DateTime) task.StartDate,
                    EndDate = task.EndDate,
                    ResourceId = task.ResourceId,
                    ProjectId = task.ProjectId,
                    TaskDuration = task.TaskDuration,
                    TaskSpent = task.TaskSpent,
                    Status = task.Status
                };
    
                new DaoTask().UpdateTask(dto);
            }
    
            public void Delete(int id)
            {
                new DaoTask().DeleteTask(id);
            }
    
            public Object PopulateDropDownLists(object task, string type)
            {
                TaskViewModels.TaskEdit taskedit;
                TaskViewModels.TaskCreate taskcreate;
                Object obj;
    
                if (type == "Create")
                {
                    taskcreate = (TaskViewModels.TaskCreate) task;
                    taskcreate.Statuses = new List<SelectListItem>
                    {
                        new SelectListItem {Value = "Planned", Text = "Planned"},
                        new SelectListItem {Value = "Started", Text = "Started"},
                        new SelectListItem {Value = "Finished", Text = "Finished"}
                    };
    
                    var selectedtask = (from a in taskcreate.Statuses.Where(a => a.Value == taskcreate.Status) select a)
                        .SingleOrDefault();
    
                    if (selectedtask != null)
                        selectedtask.Selected = true;
    
                    taskcreate.Durations = new List<SelectListItem>
                    {
                        new SelectListItem {Value = "15", Text = "15 minutes"},
                        new SelectListItem {Value = "30", Text = "30 minutes"},
                        new SelectListItem {Value = "45", Text = "45 minutes"},
                        new SelectListItem {Value = "1", Text = "1 hour"},
                        new SelectListItem {Value = "1.5", Text = "1.5 hours"},
                        new SelectListItem {Value = "2", Text = "2 hours"},
                        new SelectListItem {Value = "3", Text = "3 hours"},
                        new SelectListItem {Value = "4", Text = "4 hours"},
                        new SelectListItem {Value = "5", Text = "5 hours"},
                        new SelectListItem {Value = "6", Text = "6 hours"},
                        new SelectListItem {Value = "7", Text = "7 hours"},
                        new SelectListItem {Value = "8", Text = "8 hours"}
                    };
    
                    if (taskcreate.TaskDuration != null)
                    {
                        var selectedduration = (from a in taskcreate.Durations.Where(a => a.Value == taskcreate.TaskDuration) select a)
                            .SingleOrDefault();
    
                        if (selectedduration != null)
                            selectedduration.Selected = true;
                    }
    
                    taskcreate.Resources = new List<SelectListItem>
                    {
                        new SelectListItem {Value = "1", Text = "Intermediate Developer"},
                        new SelectListItem {Value = "2", Text = "Senior Developer"},
                        new SelectListItem {Value = "3", Text = "Junior Developer"}
                    };
    
                    if (taskcreate.ResourceId != null)
                    {
                        var selectedresource = (from a in taskcreate.Resources.Where(a => a.Value == taskcreate.ResourceId) select a)
                            .SingleOrDefault();
    
                        if (selectedresource != null)
                            selectedresource.Selected = true;
                    }
    
                    obj = taskcreate;
                }
                else
                {
                    taskedit = (TaskViewModels.TaskEdit) task;
                    taskedit.Statuses = new List<SelectListItem>
                    {
                        new SelectListItem {Value = "Planned", Text = "Planned"},
                        new SelectListItem {Value = "Started", Text = "Started"},
                        new SelectListItem {Value = "Finished", Text = "Finished"}
                    };
    
                    var selectedtask = (from a in taskedit.Statuses.Where(a => a.Value == taskedit.Status) select a)
                        .SingleOrDefault();
    
                    if (selectedtask != null)
                        selectedtask.Selected = true;
    
                    taskedit.Durations = new List<SelectListItem>
                    {
                        new SelectListItem {Value = "15", Text = "15 minutes"},
                        new SelectListItem {Value = "30", Text = "30 minutes"},
                        new SelectListItem {Value = "45", Text = "45 minutes"},
                        new SelectListItem {Value = "1", Text = "1 hour"},
                        new SelectListItem {Value = "1.5", Text = "1.5 hours"},
                        new SelectListItem {Value = "2", Text = "2 hours"},
                        new SelectListItem {Value = "3", Text = "3 hours"},
                        new SelectListItem {Value = "4", Text = "4 hours"},
                        new SelectListItem {Value = "5", Text = "5 hours"},
                        new SelectListItem {Value = "6", Text = "6 hours"},
                        new SelectListItem {Value = "7", Text = "7 hours"},
                        new SelectListItem {Value = "8", Text = "8 hours"}
                    };
    
                    if (taskedit.TaskDuration != null)
                    {
                        var selectedduration = (from a in taskedit.Durations.Where(a => a.Value == taskedit.TaskDuration) select a)
                            .SingleOrDefault();
    
                        if (selectedduration != null)
                            selectedduration.Selected = true;
                    }
    
                    taskedit.Spents = new List<SelectListItem>
                    {
                        new SelectListItem {Value = "15", Text = "15 minutes"},
                        new SelectListItem {Value = "30", Text = "30 minutes"},
                        new SelectListItem {Value = "45", Text = "45 minutes"},
                        new SelectListItem {Value = "1", Text = "1 hour"},
                        new SelectListItem {Value = "1.5", Text = "1.5 hours"},
                        new SelectListItem {Value = "2", Text = "2 hours"},
                        new SelectListItem {Value = "3", Text = "3 hours"},
                        new SelectListItem {Value = "4", Text = "4 hours"},
                        new SelectListItem {Value = "5", Text = "5 hours"},
                        new SelectListItem {Value = "6", Text = "6 hours"},
                        new SelectListItem {Value = "7", Text = "7 hours"},
                        new SelectListItem {Value = "8", Text = "8 hours"}
                    };
    
                    if (taskedit.TaskSpent != null)
                    {
                        var selectedduration = (from a in taskedit.Spents.Where(a => a.Value == taskedit.TaskSpent) select a)
                            .SingleOrDefault();
    
                        if (selectedduration != null)
                            selectedduration.Selected = true;
                    }
    
                    taskedit.Resources = new List<SelectListItem>
                    {
                        new SelectListItem {Value = "1", Text = "Intermediate Developer"},
                        new SelectListItem {Value = "2", Text = "Senior Developer"},
                        new SelectListItem {Value = "3", Text = "Junior Developer"}
                    };
    
                    if (taskedit.ResourceId != null)
                    {
                        var selectedresource = (from a in taskedit.Resources.Where(a => a.Value == taskedit.ResourceId) select a)
                            .SingleOrDefault();
    
                        if (selectedresource != null)
                            selectedresource.Selected = true;
                    }
    
                    obj = taskedit;
                }
        
                return obj;
            }
        }
    }
    
    


    Friday, March 16, 2018 4:43 PM
  • thanks for your code.

    i asked very simple thing. see the code which throw error

    List<MenuItem> query = allMenu.Where(i => i.ParentId == 0)
                    .Select(e => new MenuItem
                    {
                        Id = e.Id,
                        Name = e.Name,
                        ParentId = e.ParentId,
                        Children = allMenu.Where(x => x.ParentId == e.Id).ToList()
                    }).ToList();


    when i am querying mentuitem then i can not use menuitem to populate. how to make it possible without dto used? share idea please.

    • Edited by Sudip_inn Saturday, March 17, 2018 6:16 PM
    Saturday, March 17, 2018 6:15 PM
  • i asked very simple thing. see the code which throw error

    What error are you talking about? The only thing that I can see is that you have a circular reference possibly, because of the allMenu() being used twice with one usage being used within the Linq projection.

    Maybe, you should go into a forloop on "query" and then populate Children.

    Saturday, March 17, 2018 8:53 PM
  • Hi Sudip_inn,

    >>when i am querying mentuitem then i can not use menuitem to populate. how to make it possible without dto used? share idea please.

    According to your description and related code. I create a simple console app, it works. code below for your reference.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApp6
    {
        public class MenuItem
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int ParentId { get; set; }
            public virtual ICollection<MenuItem> Children { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                List<MenuItem> allMenu = new List<MenuItem>
                {
                    new MenuItem {Id=1,Name="Parent 1", ParentId=0},
                    new MenuItem {Id=2,Name="child 1", ParentId=1},
                    new MenuItem {Id=3,Name="child 2", ParentId=1},
                    new MenuItem {Id=4,Name="child 3", ParentId=1},
                    new MenuItem {Id=5,Name="Parent 2", ParentId=0},
                    new MenuItem {Id=6,Name="child 4", ParentId=4}
                };
    
    
                List<MenuItem> query = allMenu.Where(i => i.ParentId == 0)
                    .Select(e => new MenuItem
                    {
                        Id = e.Id,
                        Name = e.Name,
                        ParentId = e.ParentId,
                        Children = allMenu.Where(x => x.ParentId == e.Id).ToList()
                    }).ToList();
    
                foreach (var item in query)
                {
                    Console.WriteLine("{0}  ---  {1} --- {2}", item.Id, item.Name, item.ParentId);
                }
                Console.ReadLine();
            }
        }
    }
       

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Sudip_inn Thursday, March 22, 2018 12:13 PM
    Monday, March 19, 2018 1:49 AM
    Moderator