locked
Entity framework core return null in get set in asp.net core 3.0? RRS feed

  • Question

  • User342972608 posted

    I am using entity framework core asp.net core 3.0, some items return NULL values, issue in GET SET,

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using Microsoft.EntityFrameworkCore;
    using playerrate.Constants;
    using playerrate.Data.Entities;
    using playerrate.Data.Interfaces;
    using playerrate.Models;
    using playerrate.Services;
    
    namespace playerrate.Data
    {
        public class Result : Entity, IMatchResult
        {
    
            private int? _manOfMatchId;
            private int? _secondManOfMatchId;
            private int? _thirdManOfMatchId;
            private IEnumerable<IGrouping<int, ManOfMatchVote>> _manOfMatchVotesOrder;
    
            public Result()
            {
                Players = new List<GamesPlayed>();
            }
    
            public Result(IMatchResult result)
            {
                
                Date = result.Date;
                GroupId = result.GroupId;
                TeamOne = result.TeamOne;
                TeamTwo = result.TeamTwo;
                TeamOneScore = result.TeamOneScore;
                TeamTwoScore = result.TeamTwoScore;
                Players = new List<GamesPlayed>();
                ManOfMatchUserId = result.ManOfMatchUserId; 
                SecondManOfMatchUserId = result.SecondManOfMatchUserId;
                ThirdManOfMatchUserId = result.ThirdManOfMatchUserId;
                
    
    
    
    
            }
    
            [Required]
            public int GroupId { get; set; }
           
    
            public Group Group { get; set; }
       
    
            [Required]
            public DateTime Date { get; set; }
    
            [Required]
            public string TeamOne { get; set; }
    
            [Required]
            public string TeamTwo { get; set; }
    
            [Required]
            public int TeamOneScore { get; set; }
    
            [Required]
            public int TeamTwoScore { get; set; }
           //IF I USE BLOW COMMENT LINE IT WORK BUT ISSUE IS ITS CREATE ISSUE DURING UPDATE, SHOW ERROR
         //COLUMN CANNOT UPDATE MULTIPLE TIMES COLUMN LIKE THIS,
            //public int? ManOfMatchUserID { get; set; }
            //public int? SecondManOfMatchUserID { get; set; }
            //public int? ThirdManOfMatchUserID { get; set; }
            [ForeignKey("ManOfMatchUserId")]
            public User ManOfMatch { get; set; }
    
            [ForeignKey("SecondManOfMatchUserId")]
            public  User SecondManOfMatch { get; set; }
    
            [ForeignKey("ThirdManOfMatchUserId")]
            public User ThirdManOfMatch { get; set; }
    
            public ICollection<ManOfMatchVote> ManOfMatchVotes { get; set; }
            public ICollection<GamesPlayed> Players { get; set; }
    
            [NotMapped]
            public string ManOfMatchName => ManOfMatch != null ? $"{ManOfMatch.FirstName} {ManOfMatch.LastName}" : null;
            
        //I MUST WANT TO USE THESE METHODS GET SET METHOD, NEVER CHANGE BLOW GET SET METHODS,
            public int? ManOfMatchUserId
            {
                //  get;set;
                set { }
                get
                {
                    if (_manOfMatchId == null)
                    {
                        _manOfMatchId = GetManOfMatchUserId(0);
                    }
    
                    return this._manOfMatchId;
                }
            }
            public int? SecondManOfMatchUserId
            {
                set { }
                get
                {
                    if (_secondManOfMatchId == null)
                    {
                        _secondManOfMatchId = GetManOfMatchUserId(1);
                    }
    
                    return this._secondManOfMatchId;
                }
            }
            public int? ThirdManOfMatchUserId
            {
                set { }
                get
                {
                    if (_thirdManOfMatchId == null)
                    {
                        _thirdManOfMatchId = GetManOfMatchUserId(2);
                    }
    
                    return this._thirdManOfMatchId;
                }
            }
    
            [NotMapped]
            public List<int> TeamOnePlayers
            {
    
                get => Players.Where(p => p.TeamName == TeamOne).Select(p => p.UserId).ToList();
                set { }
            }
    
            [NotMapped]
            public List<int> TeamTwoPlayers
            {
                get => Players.Where(p => p.TeamName == TeamTwo).Select(p => p.UserId).ToList();
                set { }
            }
    
            [NotMapped]
            private IEnumerable<IGrouping<int, ManOfMatchVote>> ManOfMatchVotesOrder
            {
                get
                {
                    if (_manOfMatchVotesOrder == null && ManOfMatchVotes?.Any() == true)
                    {
                        var votes = this.ManOfMatchVotes.GroupBy(votes => votes.UserId);
    
                        _manOfMatchVotesOrder = votes.OrderByDescending(group => group.Count());
                    }
    
                    return _manOfMatchVotesOrder;
                }
            }
    
            private int? GetManOfMatchUserId(int index)
            {
                int? id = null;
    
    
                if (ManOfMatchVotesOrder?.Any() == true)
                {
                    var grouping = ManOfMatchVotesOrder.ElementAtOrDefault(index);
    
                    if (grouping != null)
                    {
                        id = grouping.Key;
                    }
                }
    
                return id;
            }
    
            public bool DidTeamWin(string teamName)
            {
                if (TeamTwoScore == TeamOneScore) return false;
    
                return TeamOne?.ToLower() == teamName.ToLower() ? TeamOneScore > TeamTwoScore : TeamTwoScore > TeamOneScore;
            }
    
            public int GetTeamGoalsScored(string teamName)
            {
                if (TeamOne.ToLower() == teamName.ToLower())
                {
                    return TeamOneScore;
                }
                else if (TeamTwo.ToLower() == teamName.ToLower())
                {
                    return TeamTwoScore;
                }
    
                throw new Exception($"{ErrorMessages.TeamNotFound}: {teamName}");
            }
    
            public int GetTeamGoalsConceded(string teamName)
            {
    
                if (TeamOne.ToLower() == teamName.ToLower())
                {
                    return TeamTwoScore;
                }
                else if (TeamTwo.ToLower() == teamName.ToLower())
                {
                    return TeamOneScore;
                }
    
                throw new Exception($"{ErrorMessages.TeamNotFound}: {teamName}");
            }
    
            public string GetTeamForUser(int userId)
            {
                if (TeamOnePlayers.Contains(userId))
                {
                    return TeamOne;
                }
                else if (TeamTwoPlayers.Contains(userId))
                {
                    return TeamTwo;
                }
    
                throw new Exception($"{ErrorMessages.PlayerNotFound}: {userId}");
            }
    
        }
    }

    My controller, result, its showing some values but  ManOfMatchUserId = result.ManOfMatchUserId; SecondManOfMatchUserId = result.SecondManOfMatchUserId; ThirdManOfMatchUserId = result.ThirdManOfMatchUserId;  these values are NULL, and i am sure its issue in GET set because when i try public int? ThirdManOfMatchUserId {get;set;} its working but i must use above method because its already using in application, i cannot create new one because its creating update issue,

    Controller:

      // GET: Result
            public async Task<IActionResult> Index(int? groupid)
            {
               
                var applicationDbContext = _context.Results.Include(r => r.Group).Include(r => r.ManOfMatch).Include(r => r.SecondManOfMatch).Include(r => r.ThirdManOfMatch).Where(r => r.GroupId== groupid);
                return View(await applicationDbContext.ToListAsync());
            }
    

    I have debug and here is controller debug entity result,IMAGE

    Monday, September 7, 2020 4:20 PM

All replies

  • User475983607 posted

    My controller, result, its showing some values but  ManOfMatchUserId = result.ManOfMatchUserId; SecondManOfMatchUserId = result.SecondManOfMatchUserId; ThirdManOfMatchUserId = result.ThirdManOfMatchUserId;  these values are NULL, and i am sure its issue in GET set because when i try public int? ThirdManOfMatchUserId {get;set;} its working but i must use above method because its already using in application, i cannot create new one because its creating update issue,

    The values are null because the code that instantiates the Result class does not pass a IMatchResult result in the Result constructor.  

    Can you explain how you expect the code to function?  I'm asking because the code is difficult to understand.  It does not follow EF Core or ASP.NET Core programming patterns.

    Getting Started with EF Core 

    https://docs.microsoft.com/en-us/ef/core/get-started/?tabs=netcore-cli

    Getting Started with ASP.NET Core

    https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/?view=aspnetcore-3.1

    https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/?view=aspnetcore-3.1

    Monday, September 7, 2020 6:34 PM
  • User342972608 posted

    Hi @mgehard, thanks for response, actually i have not developed this application , i am working on already developed application. I have just right click on controller and add new scaffolding and then click on create view edit,delete using entity framework using model Result context and its generated automatically generated views and controller, data on result index showing fine expected manofthematch user ids, if i use getset method in result.cs its working fine its showing and alos edit working but when i click on update it showing that cannot insert duplicate or update one column multiple times because manofthematchuserids already in IMatch result when pass two times one new i as created and previous which not working null, so its creating issue,

    I just want to show manofthematchUserId working with these get set as shown because i am afraid if i change may be its impact on other application functions where these are  using,

    Hope you understand

    Tuesday, September 8, 2020 4:43 AM
  • User1686398519 posted

    Hi hameedkhan88,

    1. According to the code and picture you provided, it is found that ManOfMatchVotes has no value, which will cause the value of ManOfMatchUserId to be empty
    2. Based on your code, when I assign a value to ManOfMatchVotes, ManOfMatchUserId has a value.
      •         public ICollection<ManOfMatchVote> ManOfMatchVotes
                {
                    get { 
                        this._ManOfMatchVotes = new List<ManOfMatchVote> { 
                        new ManOfMatchVote { UserId = 1, ManOfMatchVoteId = 1 } , 
                        new ManOfMatchVote { UserId = 2, ManOfMatchVoteId = 2 },
                        new ManOfMatchVote { UserId = 3, ManOfMatchVoteId = 3 } }; 
                        return this._ManOfMatchVotes; 
                    }
                    set {}
                }

    Here is the result.

    Best Regards,

    YihuiSun

    Tuesday, September 8, 2020 10:03 AM
  • User475983607 posted

    Meet with your team and ask them how the code is designed to work.  As written the Result class expects external code to set some of the properties which, IMHO, makes little sense for an Entity Framework type.

    Tuesday, September 8, 2020 10:42 AM