Click here to Skip to main content
16,016,022 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
hi to all,
Here i want to set default value in entities model.

DESCRIPTION:
here i set default values in controller but now i want to set default in entities model.

Here is my code in entities model:-

C#
[StringLength(1)]
      [Column(TypeName = "char")]
      public string IsActive { get; set; }


In controller:-
SQL
public ActionResult _CreatePartialView() student Student)
           {
               if (ModelState.IsValid == true)
 {
                    branch.IsActive = "Y";
               db.Students.Add(Student);
                    db.SaveChanges();
}



above code i already used but now i want to set Default value in entities model (i.e)in get set methods
Posted
Updated 4-Nov-17 0:54am

1 solution

You could set your default values in the constructor for the entity, e.g.
C#
public class MyEntity
{
    public MyEntity()
    {
        IsActive = "Maybe";
    }

    [StringLength(1)]
    [Column(TypeName = "char")]
    public string IsActive { get; set; }
}
 
Share this answer
 
Comments
JOTHI KUMAR Member 10918227 7-Aug-14 8:10am    
hmm i know this but i want to bind default value in database using entities model
[no name] 7-Aug-14 8:12am    
I thought you were using Code First? If you're creating your model from an existing database, you'd be better off setting the default value in the database and refreshing your model.
JOTHI KUMAR Member 10918227 7-Aug-14 8:26am    
hmm yeah i'm using code first migration.i cant understand what u tell can u expalin me please.
[no name] 7-Aug-14 8:33am    
If you're using Code First, the only place you can set a default value - that will be effective in all cases - is in the constructor.

You could go down the route of creating custom attributes, but in the end it'll only achieve the same thing as initializing the property from the constructor, so is a waste of time in my opinion.

Keeping it in the constructor makes future maintenance easier too as you can see all of the default values in one place.
JOTHI KUMAR Member 10918227 7-Aug-14 8:59am    
thanks for you explanation

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900