none
C#: what is the usage of virtual keyword in Entity Framework RRS feed

  • Question

  • in many mvc application i have seen people use virtual keyword. i like to know the reason.

    i have seen a video from this url https://www.youtube.com/watch?v=BSgAA8y5ViU which generate UI from model with scaffolding

    so see this code first

        public class Student
        {
            public int StudentId;
            public string StudentName;
            public int CourseId;
            public virtual Course Courses { get; set; }
        }
    
        public class Course
        {
            public int CourseId;
            public string CourseName;
            public string Description;
            public ICollection<Student> Students {get;set;}
            public ICollection<Lecture> Lectures { get; set; }
        }
    
        public class Lecture
        {
            public int LectureId;
            public string LectureName;
            public int CourseId;
            public virtual Course Courses { get; set; }
        }

    1) why lecture and student class has common property called CourseId ?

    2) see below code

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

    why they use ICollection ? they can use here list etc ?

    3) why Courses property has been declared with virtual keyword in lecture and student class ?

    please help me to understand the real use of virtual keyword

    public virtual Course Courses { get; set; }

    in what kind of scenario we use virtual keyword ? what is advantage ?

    please explain the reason why people use virtual keyword with EF ?

    thanks


    • Edited by Sudip_inn Tuesday, August 16, 2016 12:32 PM
    • Moved by CoolDadTx Tuesday, August 16, 2016 9:05 PM EF related
    Tuesday, August 16, 2016 12:29 PM

Answers

  • In the context of EF, marking a property as virtual allows EF to use lazy loading to load it. For lazy loading to work EF has to create a proxy object that overrides your virtual properties with an implementation that loads the referenced entity when it is first accessed. If you don't mark the property as virtual then lazy loading won't work with it.

    Michael Taylor
    http://www.michaeltaylorp3.net

    Tuesday, August 16, 2016 9:04 PM

All replies

  • Hi,

    as far as I see it, it is almost the same question as you asked already at: 

    https://social.msdn.microsoft.com/Forums/en-US/a14744f5-b53a-4c2a-9161-c58e08428214/when-virtual-keyword-is-used-in-c-?forum=csharpgeneral

    You marked some replies as answers so I would be interested what other information you need.

    With kind regards,

    Konrad

    Tuesday, August 16, 2016 1:01 PM
  • Hello,

    The virtual keyword allow to dereived classes  to overide this implementation


    Se a resposta for relevante ou tenha resolvido seu problema, marque como útil/resposta!

    André Secco
    Microsoft MSP & MSDN Tech Advisor
    Blog: http://andresecco.com.br
    GitHub: http://github.com/andreluizsecco
    Twitter: @andre_secco

    Tuesday, August 16, 2016 6:09 PM
  • Looks like homework for me. Honestly, your questions indicate you need to study OOP and C# a little more. For example, there are numerous benefits to using Interfaces instead of an actual Class implementation.

    What I mean is we would be happy to help, but give us an actual question, with context. Otherwise, we cannot just teach you OOP and C# concepts in one post. Hope it makes sense. Keep on learning. :)


    My Technet Articles

    If you like this or another reply, vote it up!
    If you think this or another reply answers the original question, mark it or propose it as an answer.


    Mauricio Feijo
    www.mauriciofeijo.com


    Tuesday, August 16, 2016 6:15 PM
  • And this time when giving you the answer, I will not even be missreading:

    Any class that is not marked sealed can be inherited.

    Inheritors can only hide functions with the new Keyword. Wich is hardly ever used anymore. Hiding is there because it used to be there in the beginning.

    In order for Inheritors to override that function - the much more interesting thing to do in inheritance cases - the function must be marked as Virtual, Abstract, come from a Interface (inherently abstract) or have been overridden in the base class (inherently has been virtual).

    Generally if you can not override a function, you have to do stuff like encapsulating that class into your own class.

    As properties are mostly syntax sugar for Get and Set functions, they have access to all function modifiers. Also they are one of the more interesting things you might want to override later.

    Tuesday, August 16, 2016 6:26 PM
  • >>in many mvc application i have seen people use virtual keyword. i like to know the reason.
    >>in what kind of scenario we use virtual keyword ? what is advantage ?

    For any derived class to be able to override the implementation of the member marked as virtual in the base class. Please refer to the documentation where "MyDerivedClass" inherits from "MyBaseClass" and overrides the implementation of the Number property to provided a secialized behaviour for more information: https://msdn.microsoft.com/en-us/library/9fkccyh4.aspx

    If the property had not been marked as virtual in "MyBaseClass", "MyDerviedClass" would not have been able to override it. the By default, members of a class are non-virtual.

    >>1) why lecture and student class has common property called CourseId ?

       

    Lecturer and Student don't share a common base class here. They are not related as far as the object model is concerned. You could have defined a "Person" base class and defined the CourseId in there, e.g:

    public class Person
        {
            public int CourseId;
        }
    
    public class Student : Person
        {
            public int StudentId;
            public string StudentName;
            public virtual Course Courses { get; set; }
        }
    
    
        public class Lecturer : Person
        {
            public int LectureId;
            public string LectureName;
            public virtual Course Courses { get; set; }
        }
    


    But since the model classes were auto-generated (?), they probably just map 1-to-1 with a database table and the wizard that generates the classes doesn't create a common base class for you. It can't really be supposed to know the relationship between your entities and how you want to structure your data model on the client side.

    >>why they use ICollection ? they can use here list etc ?

    Of course they can. But the creators if the wizard simply chose to use the ICollection<T> interface. Probably because it is a bit more general than IList<T> and generally you want to return a type that is as general as possible: http://stackoverflow.com/questions/9855693/returning-ilist-vs-icollection-vs-collection

    >>3) why Courses property has been declared with virtual keyword in lecture and student class ?

    For lazy loading to work. Each navigation property must be declared as public and virtual for Entity Framework to be able to create lazy loading proxy classes at runtime. Please refer to the following page for more information about this: https://msdn.microsoft.com/en-us/library/dd468057%28v=vs.100%29.aspx


    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

    • Proposed as answer by R P Sharma Tuesday, February 12, 2019 7:59 AM
    Tuesday, August 16, 2016 6:35 PM
  • In the context of EF, marking a property as virtual allows EF to use lazy loading to load it. For lazy loading to work EF has to create a proxy object that overrides your virtual properties with an implementation that loads the referenced entity when it is first accessed. If you don't mark the property as virtual then lazy loading won't work with it.

    Michael Taylor
    http://www.michaeltaylorp3.net

    Tuesday, August 16, 2016 9:04 PM