EF Code First creates and initializes a database

Source: Internet
Author: User
Tags pow

1. Preface

Code first is a new programming model provided by the Entity Framework. With code First we can start coding without having established a database, and then build the database from the object. Of course we have to do unit testing in the actual development process. In turn, the library is initialized each time it is tested so that it does not affect the test as a result of the last Test. The following is a concrete implementation.

2. Set up Object 2.1 object
/// <summary>    ///Payment Items/// </summary>     Public classFee_item:feemodel {/// <summary>    ///Payment Items/// </summary>     Public classFee_item:feemodel { PublicFee_item () {type= Feeitemtype.normal;//Enum type initialization} [Required] [Stringlength ( -, Minimumlength =2)]         Public stringName {Get;Set; }//Payment Type[Required] [Stringlength ( -, Minimumlength =2)]         Public stringCode {Get;Set; }  PublicFeeitemtype type {Get;Set; }  Public BOOLState {Get;Set; }//is enabled         Public stringIcon {Get;Set; }//Display icon         Public LongSort {Get;Set; }  Public LongAppID {Get;Set; } } [Required] [Stringlength ( -, Minimumlength =2)]         Public stringName {Get;Set; }//Payment Type[Required] [Stringlength ( -, Minimumlength =2)]         Public stringCode {Get;Set; }  PublicFeeitemtype type {Get;Set; }  Public BOOLState {Get;Set; }//is enabled         Public stringIcon {Get;Set; }//Display icon         Public LongSort {Get;Set; }  Public LongAppID {Get;Set; } }
View Code2.2 Assigning a default value to an object "selectable"
     Public voidInitialize (Feedbcontext context) {List<fee_item> FIM =NewList<fee_item>() {                 NewFee_item () {name="Electricity", code="POW", Type= feeitemtype.normal,state=true, icon="Img/jf_dianf.png", sort=0, appid=0, reg_time=DateTime.Now},NewFee_item () {name="Net fee", code="Net", Type= feeitemtype.normal,state=true, icon="Img/jf_wangf.png", sort=1, appid=1, reg_time=DateTime.Now},NewFee_item () {name="level 46", code="CET", Type= feeitemtype.normal,state=true, icon="Img/jf_siliuj.png", sort=2, appid=2, reg_time=DateTime.Now},NewFee_item () {name="Registration Fee", code="POW", Type= feeitemtype.normal,state=true, icon="Img/jf_baomingf.png", sort=3, appid=3, reg_time=DateTime.Now},NewFee_item () {name="Insurance Premiums", code="POW", Type= feeitemtype.normal,state=false, icon="Img/jf_baox.png", sort=4, appid=4, reg_time=DateTime.Now},NewFee_item () {name="Accommodation fee", code="POW", Type= feeitemtype.normal,state=true, icon="Img/jf_dianf.png", sort=5, appid=5, reg_time=DateTime.Now}}; List<school_power> Con_power =NewList<school_power>() {             NewSchool_power () {oid=1, power_code="Ykt", power_id="1", reg_time=DateTime.Now},NewSchool_power () {oid=1, power_code="Sims", power_id="2", reg_time=DateTime.Now}}; Fim. ForEach (o=Context.fee_item.           ADD (o)); Context.        SaveChanges (); }
View Code3.DBContext
   Public classFeedbcontext:dbcontext { PublicFeedbcontext ():Base("Feedbcontext") { }         PublicDbset<fee_item> Fee_item {Get;Set; } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {Base.            Onmodelcreating (ModelBuilder); ModelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); }    }
View Code4.EF Code First4.1 New
 Public BOOLBuild () {Try            {                varContext =NewFeedbcontext (); if(!context. Database.exists ()) {NewList<idatainitializer<feedbcontext>>() {                         Newdatainit4dept ()}. Setup<FeeDbContext>(context); return true; }                return false; }            Catch(Dbentityvalidationexception ex) {StringBuilder error=NewStringBuilder (); foreach(varIteminchEx. entityvalidationerrors) {foreach(varItem2inchitem. validationerrors) {error. Append (string. Format ("{0}:{1}\r\n", item2. PropertyName, Item2.                    errormessage)); }} Console.WriteLine ("Database initialization error:"+error); Throwex; }            Catch(Exception e) {Console.WriteLine ("Database initialization error:"+e.message); Throwe; }        }
View Code4.2 Removal
  Public BOOLRemove () {varContext =NewFeedbcontext (); Try            {                if(context. Database.exists ()) {returncontext.                Database.delete (); }                return true; }            Catch(Exception e) {Console.WriteLine ("Database initialization error:"+e.message); return false; }            finally{context. Dispose (); }        }
View Code4.3 initialization
 Public BOOL Rebuild ()        {            return Remove () && Build ();        }
View Code

EF Code First creates and initializes a database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.