In this tutorial, I’ll explain how to initialize Entity Framework Code First views with default values. Entity Framework Code First provides a declarative method for easily creating CRUD applications with the ASPASP Dot Net MVC framework.
To get started, I’ll assume you already have your model in place and have auto-generated your controller and views. If you don’t have these set up, check out this tutorial for getting started with Entity Framework and MVC.
I solve the default value problem using constructors. Other solutions exist, but initializing values in a constructor is a valid approach that other developers with an object-oriented background will immediately understand. Open the model whose instances you want initialized and, just beneath the class declaration, add a constructor as shown below.
public class Order
{
public Order()
{
Quantity = 1;
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public int Quantity { get; set; }
public string CustomerName { get; set; }
}
The final step is to pass an instance of the model to your Razor view. Newing an instance of the model calls its constructor, giving the Razor @model
an initialized object with which to get values from. In the GET Create
method of your controller, modify the call to View
by instantiating an instance of your model.
// GET: Orders/Create
public ActionResult Create()
{
return View(new Order());
}
If you build and run your application, you will see that the create view now has the default values you set in the constructor.