Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

c# - Setting default value in entity framework - Database First

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;} }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...