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?
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.
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.
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.
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.
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;
}
}
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 */
}
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 };
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