none
MVC Group Join - Returns duplicate values in View

    Pertanyaan

  • Greetings

    I trust you are well. Could anybody possibly assist with linq group join into viewmodel. For some strange reason my list returns duplicates even though I have utilized the Distinct() method at the end of controller.

    I have used the Guid class to create a relationship between 2 objects. When the view is rendered, duplicates show up. Could someone please assist.

    Thanks

    [HttpGet]
    public ActionResult ClientAADetails(string ClientId)
    {

    var query = (from z in db.ClientFileUploaded
    join x in db.WorkingPaperAAs on z.ClientId equals x.ClientId
    where x.ClientId == ClientId
    select new ClientAADetails()
    {
    Id = x.Id,
    ClientId = x.ClientId,
    ClientName = x.ClientName,
    ClientIDnumber = x.ClientIDnumber,
    MaritalRegime = x.MaritalRegime,
    EstateLate = x.EstateLate,
    PreparedBy = x.PreparedBy,
    PreparedByDate = x.PreparedByDate,
    ReviewedBy = x.ReviewedBy,
    ReviewedByDate = x.ReviewedByDate,

    HusbandName = x.HusbandName,
    HusbandAmount = x.HusbandAmount,
    HusbandInterest = x.HusbandInterest,
    HusbandComments = x.HusbandComments,

    HusbandName1 = x.HusbandName1,
    HusbandAmount2 = x.HusbandAmount2,
    HusbandInterest3 = x.HusbandInterest3,
    HusbandComments4 = x.HusbandComments4,

    HusbandName5 = x.HusbandName5,
    HusbandAmount6 = x.HusbandAmount6,
    HusbandInterest7 = x.HusbandInterest7,
    HusbandComments8 = x.HusbandComments8,

    HusbandName9 = x.HusbandName9,
    HusbandAmount10 = x.HusbandAmount10,
    HusbandInterest11 = x.HusbandInterest11,
    HusbandComments12 = x.HusbandComments12,

    WifeName = x.WifeName,
    WifeAmount = x.WifeAmount,
    WifeInterest = x.WifeInterest,
    WifeComments = x.WifeComments,

    WifeName1 = x.WifeName1,
    WifeAmount2 = x.WifeAmount2,
    WifeInterest3 = x.WifeInterest3,
    WifeComments4 = x.WifeComments4,

    WifeName5 = x.WifeName5,
    WifeAmount6 = x.WifeAmount6,
    WifeInterest7 = x.WifeInterest7,
    WifeComments8 = x.WifeComments8,

    WifeName9 = x.WifeName9,
    WifeAmount10 = x.WifeAmount10,
    WifeInterest11 = x.WifeInterest11,
    WifeComments12 = x.WifeComments12,

    TotalAmount = x.TotalAmount,

    DetailedscheduleofaccountsReceived = x.DetailedscheduleofaccountsReceived,
    DebtorsconfirmationofbalancesReceived = x.DebtorsconfirmationofbalancesReceived,
    DebtorsstatementsReceived = x.DebtorsstatementsReceived,

    DetailedscheduleofaccountsComments = x.DetailedscheduleofaccountsComments,
    DebtorsconfirmationofbalancesComments = x.DebtorsconfirmationofbalancesComments,
    DebtorsstatementsComments = x.DebtorsstatementsComments,

    Obtainscheduleofdebtorswithnamesaddressrepaymentterms = x.Obtainscheduleofdebtorswithnamesaddressrepaymentterms,
    Obtainwrittenconfirmationfromdebtorofamountowing = x.Obtainwrittenconfirmationfromdebtorofamountowing,
    Ensurethatschedulesignedbyexecutor = x.Ensurethatschedulesignedbyexecutor,

    WorkingPaper1 = x.WorkingPaper1,
    WorkingPaper2 = x.WorkingPaper2,
    WorkingPaper3 = x.WorkingPaper3,

    Signature1 = x.Signature1,
    Signature2 = x.Signature2,
    Signature3 = x.Signature3,

    Date1 = x.Date1,
    Date2 = x.Date2,
    Date3 = x.Date3,

    Comment1 = x.Comment1,
    Comment2 = x.Comment2,
    Comment3 = x.Comment3,

    FileId = z.Id,
    File = z.File,
    FileName = z.FileName,
    File2 = z.File2,
    FileName2 = z.FileName2,
    File3 = z.File3,
    FileName3 = z.FileName3,
    File4 = z.File4,
    FileName4 = z.FileName4,
    File5 = z.File5,
    FileName5 = z.FileName5,
    File6 = z.File6,
    FileName6 = z.FileName6,
    File7 = z.File7,
    FileName7 = z.FileName7,
    File8 = z.File8,
    FileName8 = z.FileName8

    }).Distinct();

    if (query == null)
    {
    return View("Notfound");
    }

    var data = db.WorkingPaperAAs.Where(d => d.ClientId == ClientId);
    double? HusbandSum1 = data.Sum(d => d.TotalAmount);

    var regime = (from x in db.NewEstates
    where x.ClientId == ClientId
    select x.Marital_Regime).FirstOrDefault();

    var status = (from z in db.NewEstates
    where z.ClientId == ClientId
    select z.Marital_Status).FirstOrDefault();

    var fname = (from c in db.NewEstates
    where c.ClientId == ClientId
    select c.FirstName).FirstOrDefault();

    var sname = (from c in db.NewEstates
    where c.ClientId == ClientId
    select c.Surname).FirstOrDefault();

    string fullname = string.Concat(fname, " ", sname);

    ViewBag.abc = fullname;

    ViewBag.status = status;

    ViewBag.regime = regime;

    ViewBag.v = HusbandSum1;

    return View(query.Distinct());
    }


    • Dipindahkan oleh CoolDadTxMVP Kamis, 27 September 2018 14.25 ASP.NET related
    Rabu, 26 September 2018 08.02

Semua Balasan

  • I will say this. You have the controller doing things like data access that it shouldn't be doing. However, MVC can be discussed at the  ASP.NET forums.

    http://forums.asp.net/

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs

    <copied>

    An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.

    A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.

    In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.

    <end>

    Example code, as you have more code in a Action Method than the controller code example that has many Action Methods in it.

    using System;
    using System.Linq;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.ModelBinding;
    using ProgMgmntCore2UserIdentity.Models;
    
    namespace ProgMgmntCore2UserIdentity.Controllers
    {
        public class ProjectController : Controller
        {
            private readonly IProjectModel _projectModel;
            private readonly IModelHelper _modelHelper;
           
            public ProjectController(IProjectModel projectModel,   IModelHelper modelHelper)
            {
                _projectModel = projectModel;
                _modelHelper = modelHelper;
            }
    
            // GET: Project
            [Authorize]
            public ActionResult Index()
            {
                return View(_projectModel.GetProjectsByUserId(User.Identity.Name));
            }
    
            [Authorize]
            public ActionResult Details(int id = 0)
            {
                return id == 0 ? null : View(_projectModel.Edit(id));
            }
    
            [Authorize]
            public ActionResult Create()
            {
                return View(_projectModel.Create());
            }
    
            [Authorize]
            [HttpPost]
            public ActionResult Create(ProjectViewModels.Project project, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                ValidateddlProjectTypes();
    
                project.ProjectType = (Request.Form["ddlProjectTypes"]);
    
                if (ModelState.IsValid && _modelHelper.IsEndDateLessThanStartDate(project, "Project"))
                    ModelState.AddModelError(string.Empty, "End Date cannot be less than Start Date.");
    
                if (!ModelState.IsValid) return View(_projectModel.PopulateSelectedList(project));
    
                _projectModel.Create(project, User.Identity.Name);
                return RedirectToAction("Index");
            }
    
            [Authorize]
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(_projectModel.Edit(id));
            }
    
            [Authorize]
            [HttpPost]
            public ActionResult Edit(ProjectViewModels.Project project, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                if (ModelState.IsValid && _modelHelper.IsEndDateLessThanStartDate(project, "Project"))
                    ModelState.AddModelError(String.Empty, "End Date cannot be less than Start Date.");
    
                if (!ModelState.IsValid) return View(_projectModel.PopulateSelectedList(project));
    
                var theproject = new ProjectViewModels.Project();
    
                theproject = project;
    
                theproject.ProjectType = Request.Form["ProjectType"];
    
                _projectModel.Edit(theproject, User.Identity.Name);
                return RedirectToAction("Index");
            }
    
            public ActionResult Delete(int id = 0)
            {
                if (id > 0) _projectModel.Delete(id);
    
                return RedirectToAction("Index");
            }
       
            public ActionResult Cancel()
            {
                return RedirectToAction("Index", "Home");
            }
    
            public ActionResult UploadFile(int id)
            {
                return RedirectToAction("Index", "Upload", new { id = id, type = "PM" });
            }
    
            private void ValidateddlProjectTypes()
            {
                if (Request.Form["ddlProjectTypes"] == string.Empty)
                  return;
           
                foreach (var key in ModelState.Keys.ToList().Where(key => ModelState.ContainsKey(key)))
                {
                    if (key != "ProjectType") continue;
                    ModelState[key].Errors.Clear();
                    ModelState[key].ValidationState = ModelValidationState.Valid;
                }
            }
        }
    }

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Entities;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.Extensions.Caching.Memory;
    using ProgMgmntCore2UserIdentity.WebApi;
    
    namespace ProgMgmntCore2UserIdentity.Models
    {
        public class ProjectModel : IProjectModel
        {
            private readonly IMemoryCache _memoryCache;
            private readonly IWebApi _webApi;
    
            public ProjectModel(IWebApi webApi, IMemoryCache memoryCache)
            {
                _memoryCache = memoryCache;
                _webApi = webApi;
            }
    
            public ProjectViewModels GetProjectsByUserId(string userid)
            {
                var vm = new ProjectViewModels {Projects = new List<ProjectViewModels.Project>()};
    
                var dtos = _webApi.GetProjsByUserIdApi(userid).ToList();
                
                vm.Projects.AddRange(dtos.Select(dto => new ProjectViewModels.Project()
                {
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                }).ToList());
    
                return vm;
            }
    
            public ProjectViewModels.Project GetProjectById(int id)
            {
                var responseDto = _webApi.GetProjByIdApi(id);
    
                var project = new ProjectViewModels.Project
                {
                    ProjectId = responseDto.ProjectId,
                    ClientName = responseDto.ClientName,
                    ProjectName = responseDto.ProjectName,
                    Technology = responseDto.Technology,
                    ProjectType = responseDto.ProjectType,
                    StartDate = responseDto.StartDate,
                    EndDate = responseDto.EndDate,
                    Cost = responseDto.Cost
                };
    
                return project;
            }
    
            public ProjectViewModels.Project Create()
            {
                var project = new ProjectViewModels.Project();
                return PopulateSelectedList(project);
            }
    
            public void Create(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,  
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                _webApi.CreateProjectApi(dto);
            }
    
            public ProjectViewModels.Project Edit(int id)
            {
                var responseDto = _webApi.GetProjByIdApi(id);
    
                var project = new ProjectViewModels.Project
                {
                    ProjectId = responseDto.ProjectId,
                    ClientName = responseDto.ClientName,
                    ProjectName = responseDto.ProjectName,
                    Technology = responseDto.Technology,
                    ProjectType = responseDto.ProjectType,
                    StartDate = responseDto.StartDate,
                    EndDate = responseDto.EndDate,
                    Cost = responseDto.Cost
                };
    
                project = PopulateSelectedList(project);
    
                return project;
            }
    
            public void Edit(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                _webApi.UpdateProjectApi(dto); 
            }
    
            public void Delete(int id)
            {
                _webApi.DeleteProjectApi(new DtoId{Id = id});
            }
    
            public ProjectViewModels.Project PopulateSelectedList(ProjectViewModels.Project project)
            {
                bool isExist = _memoryCache.TryGetValue("DtoCache", out DtoCache dtocache);
    
                if (!isExist)
                {
                    dtocache = _webApi.GetCacheApi();
              
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                        .SetSlidingExpiration(TimeSpan.FromSeconds(30));
                    
                    _memoryCache.Set("DtoCache", dtocache, cacheEntryOptions);
                }
    
                project.ProjectTypes = new List<SelectListItem>();
    
                foreach (var pt in dtocache.ProjectTypes)
                {
                    var sli = new SelectListItem {Value = pt.Value, Text = pt.Text};
                    project.ProjectTypes.Add(sli);
                }
           
                var selected = (from a in project.ProjectTypes.Where(a => a.Value == project.ProjectType) select a)
                    .SingleOrDefault();
    
                if (selected != null)
                    selected.Selected = true;
    
                return project;
            }
        }
    }
    

    Rabu, 26 September 2018 20.43
  • Please post questions related to MVC in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Kamis, 27 September 2018 14.25