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!

3
  • 1
    You should probably put default values in your database definition. Commented Oct 2, 2012 at 14:09
  • Since this is not code first then MrFox has the right idea. Commented Oct 2, 2012 at 14:18
  • I could do that, but I would like to avoid it if at all possible. Commented Oct 2, 2012 at 14:36

2 Answers 2

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;} }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Ah, yep... danger of writing code without an IDE :-) you probable just need to declare the property as virtual..?
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". ???
you probably need to declare that member as virtual?
2

You use OnCreated on the partial class:

public partial class ENTITY
{    
  partial void OnCreated()
  {
    DESCRIPTION_ = "default string";
  } 
}

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.