Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing default values in a Model

Tags:

c#

asp.net-mvc

In a C# MVC application, I have a Model, Customer, which can be retrieved from the database, or created as new.

If I am creating a new Customer what is the proper way to set default values (such as CusotmerLevel defaults to 1)?

Should I have different constructors for a new employee and an employee retrieved from the database, or some other way?

like image 850
A Bogus Avatar asked Apr 09 '13 12:04

A Bogus


People also ask

How do I set default value in model class?

You can use the Factory pattern to create a new customer. This way you can give the Factory the responsability of setting the correct default values. If not usable i would set it in the default constructor.

Can we set default values for model?

In practice, you could create the ViewModel, and override these defaults with values pulled from a database entry (using the data-backed model), but as-is, this will always use these default values.

How can default value be set?

Set a default valueIn the Navigation Pane, right-click the form that you want to change, and then click Design View. Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value.

What is the purpose of a default value?

Default values, in the context of databases, are preset values defined for a column type. Default values are used when many records hold similar data.


2 Answers

Assuming it's a POCO, I've always found the constructor is fine for establishing default values. I usually take that opportunity to declare things like CreatedDate. When it's retrieved from the database, the public properties will be overridden by the database values anyways.

public class Customer
{
    public Int32 Id { get; set; }
    public Int32 CustomerLevel { get; set; }
    /* other properties */

    public Customer()
    {
        this.CustomerLevel = 1;
    }
}

Update

And, if you're using C# 6.0 check out auto-property initializers:

public class Customer
{
    public Int32 Id { get; set; } = 1;
    public Int32 CustomerLevel { get; set; }
    /* other properties */
}
like image 62
Brad Christie Avatar answered Sep 22 '22 18:09

Brad Christie


Use the default constructor, all the ORMs I've tried set values after the constructor is run so it should not interfere.

One alternative method would be:

 var customer = new Customer() { CustomerLevel=1 };
like image 28
AlexanderBrevig Avatar answered Sep 21 '22 18:09

AlexanderBrevig