EntityFramework 5.0 Codefirst Tutorial 03-Definition/Column properties of a data structure

Source: Internet
Author: User

---------------------Directory--------------------------

EntityFramework 5.0 Codefirst Tutorial 03-Definition/Column properties of data Structures (2015-07-22 17:30)

EntityFramework 5.0 Codefirst Tutorial 02-Delete and modify/Schema change exception handling (2015-07-14 17:50)

EntityFramework 5.0 Codefirst Tutorial 01-Build the environment and get started quickly (2015-07-13 10:48)

---------------------Directory--------------------------

First of all, thank you for your support, more busy recently, but will take the time to finish the code first thank you for your support want more learning resources, can visit my homepage, thank you

This episode we'll learn to define a data structure, first look. NET type and SQL type, the left side is the SQL type, and the right is. NET Type

1 Configuring Simple properties here, we continue to use the person class to configure the properties, the following code is modified:
  Public classPerson { Public intPersonId {Get;Set; } [MaxLength ( -)]         Public stringFirstName {Get;Set; } [MaxLength ( -)]         Public stringLastName {Get;Set; } [Stringlength (1, Minimumlength =1)] [Column (TypeName="Char")]         Public stringMiddleName {Get;Set; } }

Some attribute annotations have been added to each attribute, where maxlength (30) indicates that the maximum length of the field is 30,stringlength for the minimum length and maximum length minimumlength

[Column (TypeName = "char")] means that the column property is a char type

Need to reference System.ComponentModel.DataAnnotations this assemblybelow we write the following code and then execute the
Static voidMain (string[] args) {            //more information can be logged into my homepage: www.bamn.cn welcome Everyone            using(varPersoncontext =NewContext ()) {                //If the database does not exist, create                BOOLres =personContext.Database.CreateIfNotExists (); //adding data to the database                varperson =NewPerson {FirstName="John", LastName="Doe", MiddleName="Mid"                };                PERSONCONTEXT.PEOPLE.ADD (person);                Personcontext.savechanges (); //Get Data                varSavedpeople =personcontext.people; foreach(varPinchsavedpeople) {Console.WriteLine ("Last name:{0},first name:{1},id {2},mid={3}", P.lastname, P.firstname, p.personid,p.middlename);        }} console.readkey (); }

We need to quote the following exception when we faint-write the code.unhandled exception of type "System.InvalidOperationException" occurs in EntityFramework.dllAdditional information: The model backing the ' context ' context has changed since, the database was created. Consider using Code first migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269). We later to solve this problem, the following temporary solution, first we delete our database, even if the previously connected database Efdemo deleted, we run the discovery or report the following exceptionunhandled exception of type "System.Data.Entity.Validation.DbEntityValidationException" occurs in EntityFramework.dllAdditional information: Validation failed for one or more entities. See ' entityvalidationerrors ' property for more details.But when we visited the database, we found that our tables had been created Here we have to say, that is, we use code First we do not have to create a good databaseHere we have to pay attention and then we find that our database fields have corresponding properties, such as FirstName is the length of nvarchar 30 and then MiddleName is Char One so you should know what the mistake we just made was, so we changed the code above to execute the code again. If the user enters a name more than 30 bytes, we should give an error
[MaxLength (" your name exceeds 30 bytes ")]  Public string Get set; }

The error message here is to support internationalization, which can be other languages this set of all the code:
classProgram {Static voidMain (string[] args) {            //more information can be logged into my homepage: www.bamn.cn welcome Everyone            using(varPersoncontext =NewContext ()) {                //If the database does not exist, create                BOOLres =personContext.Database.CreateIfNotExists (); //adding data to the database                varperson =NewPerson {FirstName="John", LastName="Doe", MiddleName="M"                };                PERSONCONTEXT.PEOPLE.ADD (person);                Personcontext.savechanges (); //Get Data                varSavedpeople =personcontext.people; foreach(varPinchsavedpeople) {Console.WriteLine ("Last name:{0},first name:{1},id {2},mid={3}", P.lastname, P.firstname, p.personid,p.middlename);        }} console.readkey (); }    }  Public classPerson { Public intPersonId {Get;Set; } [MaxLength ( -, errormessage ="your name is over 30 bytes.")]         Public stringFirstName {Get;Set; } [MaxLength ( -)]         Public stringLastName {Get;Set; } [Stringlength (1, Minimumlength =1)] [Column (TypeName="Char")]         Public stringMiddleName {Get;Set; } }     Public classContext:dbcontext { PublicContext ():Base("Name=chapter2")        {        }         Publicdbset<person> people {Get;Set; } }

Thank you for reading: This set code download: Http://pan.baidu.com/s/1gdlgRbP

EntityFramework 5.0 Codefirst Tutorial 03-Definition/Column properties of a data structure

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.