Simple Example of ADO. NET Entity Framework and Code First, ado. netentity

Source: Internet
Author: User

Simple Example of ADO. NET Entity Framework and Code First, ado. netentity

1. Install EntityFramework;

Open NuGet in vs and enter Install-Package EntityFramework in the command line.

Ii. Basic usage

1. Create a data model

Class Student {public int id {get; set ;}// ID public string name {get; set ;}// name public byte age {get; set ;}// age}

2. Create a data context

Using System. data. entity; // reference Entity Frameworknamespace SQL {class StudentContext: DbContext {public StudentContext (): base (@ "Data Source = MYPC \ MSSQLSERVER; Initial Catalog = entitycodefirst; User ID = sa; password = 123456 ") {} public DbSet <Student> Students {get; set ;}}}

3. Use

Using System; namespace SQL {class Program {static void Main (string [] args) {// save using (var data = new StudentContext () {var student1 = data. students. create (); // Create a student's object student1.name = "Tom"; student1.age = 15; data. students. add (student1); // Add the student object to the student table var student2 = data. students. create (); student2.name = "Xiaohong"; student2.age = 15; data. students. add (student2); data. saveChanges (); // save it to the database} // read using (var data = new StudentContext () {foreach (var item in data. students) {Console. writeLine ("ID: {0}, name: {1}, age: {2}", item. id, item. name, item. age) ;}} Console. readKey (true );}}}

 

Related Article

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.