Setting default value in entity framework - Database First
Asked Answered
A

2

5

I am using Entity Framework 4.3.1, with auto-generated entities from the database.

From this, is there any way to set the default value to something? I don't want to put it in the auto-generated code since it will be overwritten.

I understand that it is possible to use partial classes, so I tried something like this, where entity is generated, and DESCRIPTION_ is the attribute I want to set to a default value.

namespace name.Models
{
    public partial class ENTITY
    {
        public string DESCRIPTION_
        {
            set { _DESCRIPTION_ = "default string"; }
        }
    }
}

Maybe if somebody could give me an example that would be great!

Achondroplasia answered 2/10, 2012 at 14:6 Comment(3)
You should probably put default values in your database definition.Reardon
Since this is not code first then MrFox has the right idea.Felipa
I could do that, but I would like to avoid it if at all possible.Achondroplasia
S
4

The example you give means that DESCRIPTION can only ever be "default string"

You can set it in the constructor

namespace name.Models 
{
  public partial class ENTITY
  {
    private string defaultDescription = "some text";
    public ENTITY() {
      DESCRIPTION_ = defaultDescription;
    } 
  }
}

or by switching your property to one with a backing field

namespace name.Models
{
    public partial class ENTITY
    {
        private string _desc = "some default value"; 
        public virtual string DESCRIPTION_ {get {return _desc} set {_desc = value;} }
    }
}
Shod answered 2/10, 2012 at 14:11 Comment(4)
Hey thanks! I tried both but it doesn't seem to work. The 2nd tells me there is ambiguity as it is defined twice(since its already defined in the ADO.net entity code). Basically im using asp.net MVC, to check if the user adds text to a certain field, if not the model should add default value.Achondroplasia
Ah, yep... danger of writing code without an IDE :-) you probable just need to declare the property as virtual..?Niphablepsia
I don't see how you got this to work. In the first case, I get that same error "Type 'OTIS.Models.Admin.Company' already defines a member called 'Company' with the same parameter types". ???Decussate
you probably need to declare that member as virtual?Niphablepsia
I
2

You use OnCreated on the partial class:

public partial class ENTITY
{    
  partial void OnCreated()
  {
    DESCRIPTION_ = "default string";
  } 
}
Interrogatory answered 2/10, 2012 at 14:10 Comment(1)
Hey, thanks for the quick reply! I tried that, but i get error No defining declaration found for implementing declaration of partial method. Forgot to mention that I am using asp.net MVC.Achondroplasia

© 2022 - 2024 — McMap. All rights reserved.