I am working on a project in ASP.NET MVC
. I've been looking for some learning resources regarding the subject and I've come across a scenario which I'm searching for clarification. Suppose:
public class Foo
{
public int Id { get; set; }
public string FooName { get; set; }
public virtual Bar Bar { get; set; }
}
and
public class Bar
{
public Bar()
{
this.Foos = new List<Foo>;
}
public int Id { get; set; }
public string BarDesc { get; set; }
public virtual List<Foo> Foos { get; set; }
}
I mean, in what way does it differ from that of a model Bar with no constructor? Please disregard any errors in the properties (if there any) or possible relationship within entities, since I just want clarification about having a constructor inside a model. Thanks!
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.
@model is used to "import" a model in the view page while the @Model represents the imported model and is where you retrieve its properties. Here you see that @model simply imports the Model object to the page while the @Model you get actual value from the retrieved model.
If they mean, can you implement the MVC pattern without a model, then the answer is no. The M means Model. Save this answer.
In fact, in ASP.NET MVC, there are three distinct types of model: the domain model, view model and input model.
With the constructor you've shown, Bar.Foos
will be an empty List of type Foo.
Without the constructor, Bar.Foos
will be null (unless you initialize it elsewhere).
It's the same difference you'd see between these two lines:
List<SomeType> test1 = null;
List<SomeType> test2 = new List<SomeType>();
Assuming you're using C# 6, another way of initializing it without a constructor is:
public class Bar
{
public int Id { get; set; }
public string BarDesc { get; set; }
public virtual List<Foo> Foos { get; set; } = new List<Foo>();
}
Which of the 3 techniques you choose will be up to you, based on whether you always want the property to be initialized or not, if you have multiple constructors, which you think looks better, how you feel about null collection references vs empty collections etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With