EF 6 codde first - One To Many Mapping - ICollection always null

asp.net-mvc c# dbcontext ef-code-first entity-framework-6

Question

I am aware that this subject has been raised before, but I am experiencing weird behaviour and have been unable to find an answer.

I'm using EF6 and code first to create a.Net application. The following is how I defined my classes (these are just examples; my classes all have the same structure):

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int RefId { get; set; }

    public int GradeId { get; set; }
    public Grade Grade { get; set; }
}

public class Grade
{
    private string _name;

    public int GradeId { get; set; }
    public string GradeName { get; set; }

    public ICollection<Student> Students { get; set; }
}

I am aware that, from ef 4, lazy loading is enabled by default; the majority of the time, the remedy is to remove the virtual keyword from the entities (non-virtual properties).

In my situation, I want to add some custom logic to the Grade class' getter function, howeverICollection<Student> Students is never null.

For instance:

public string GradeName
{
    get
    {
        _name = Students.FirstOrDefault(s => s.GradeId == GradeId &&
                              s.RefId == 2).Name;

        if (string.IsNullOrWhiteSpace(_name))
        {
            _name = Name;
        }

        return _name;
    }

    set => _name = value;
}

I made every effort, but nothing worked. I would appreciate it if you could assist me in resolving this problem.

1
0
12/22/2017 5:40:13 AM

Popular Answer

ZZZ_tmp
1
12/21/2017 11:12:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow