Entity Framework Notes (i)

Source: Internet
Author: User
Tags connectionstrings

Recently, looking at MVC, I've seen several tutorials that use the Entity Framework for data persistence. I've heard about this before, and I've seen a demo video on Microsoft's website, but I haven't done much research. The MVC thing is too big to be familiar with first. However, you can start with one of these parts and learn the entity FrameWork first. As notes, which day turned out warm.

Simply put, EF is an ORM solution, something Microsoft is out of. Here, the main record how to use, as to its ins and outs, you can search online. Start creating the console project with VS2010 and use EF as a tool for working with databases. To use the EF framework in VS2010, you'll need to install the plugin: NuGet, click the link below https://visualstudiogallery.msdn.microsoft.com/ 27077b70-9dad-4c64-adcf-c7cf6bc9970c, install after download.

Create a new console project and name Efconsoledemo. Right-click the project and see the "Manage NuGet packages" item on the menu, and after clicking on the pop-up form, search for the entity famework, and then the installation after the dot. The middle will pop up whether or not to agree to the installation, click "I agree" to complete.

Right-click on the project to manage "NuGet packages"

After you have searched the Entity Framework, install it after the point (if it is not installed, there will be an install button in the green tick)

At this point we see a pakages.config file in the project, expand the reference, you will find a few more entityframework related references. This is where the user of the EF code First mode is recorded. Next, configure the database connection string to add the following configuration in the App. Config file:

<connectionStrings>    <add name= "Userdal" providername= "System.Data.SqlClient" connectionstring= "Data Source = localhost; Initial Catalog = TestDb; Integrated Security = true "/>  </connectionStrings>

You need to be aware of the Name property of the connection string, and the next time you create the class, you need to keep the name consistent. Next, create the class, as an example of a simple user management. Assuming that the user table requires a Id,username,userpwd,email,tel field, you need to create one user class and paste the code directly. The [key] property on the ID indicates that the field that the attribute is mapped to in the database table is the primary key.

    Public classUsers {[Key] Public intUserId {Get;Set; }  Public stringUserName {Get;Set; }  Public stringuserpwd {Get;Set; }  Public stringEmail {Get;Set; }  Public stringTel {Get;Set; } }

The next point is to create the code that deals with the database. Note that the class name Userdal here needs to be consistent with the Name property of the connection string in app. Config. Override the Onmodelcreating method to map the user class above to the T_users table in the database.

 public  class   Userdal:dbcontext { protected  over Ride  void   onmodelcreating ( Dbmodelbuilder modelBuilder) {modelbuilder.entity  <Users> (). ToTable ( t_users   "            );  base   public  dbset<users> Users {get
      ; set     

Return to the Program.cs file in your project, create an instance for the user class, and insert the instance value into the database.

  classProgram {Static voidMain (string[] args) {Operationclass Operation=NewOperationclass (); Users User=operation.            Inituser (); Operation.            Saveuser (user); Operation.            Displayusers ();        Console.readkey (); }    }     Public classOperationclass { PublicUsers Inituser () {stringUserName =string.            Empty; stringUserpwd =string.            Empty; stringEmail =string.            Empty; stringTel =string.            Empty; Users User=NewUsers (); Console.WriteLine ("Input UserName:"); UserName=Console.ReadLine (); Console.WriteLine ("Input userpwd"); Userpwd=Console.ReadLine (); Console.WriteLine ("Input UserEmail"); Email=Console.ReadLine (); Console.WriteLine ("Input Usertel"); Tel=Console.ReadLine (); User. UserName=UserName; User. Userpwd=userpwd; User. Email=Email; User. Tel=Tel; returnuser; }         Public voidsaveuser (Users user) {Userdal userdal=NewUserdal ();            USERDAL.USERS.ADD (user);        Userdal.savechanges (); }         Public voidDisplayusers () {Console.WriteLine ("Display all Users in the System:"); Console.WriteLine ("***************************************************"); Userdal Userdal=NewUserdal (); List<Users> Users =userDal.users.ToList (); foreach(Users Iteminchusers) {Console.WriteLine ("UserName: {0}", item.                UserName); Console.WriteLine ("userpwd: {0}", item.                USERPWD); Console.WriteLine ("useremail: {0}", item.                Email); Console.WriteLine ("Usertel: {0}", item.                Tel); Console.WriteLine ("*****------**********---------********"); } Console.WriteLine ("All Users Displayed."); }    }

Run the project. When the data is first run, EF automatically creates the T_users table in TestDB and inserts the entered data into the database. In the display method, the ToList method of the Users property in Userdal is called to get all the data in the data table. Therefore, when the data is entered for the second time, the second piece of data is inserted into the table and output two data. At this point, using EF in VS 2010 has been successful. What's the convenience of bringing us? First, you do not have to create tables in the database (or write SQL script generation); You do not need to write INSERT statements and query statements. The framework completes a relational mapping of objects and data for us. However, the problem is that, in our project, it is not possible to use only two simple operations such as inserting and querying all data. We also need to delete, modify, conditionally query and so on complex database operations.

Cond.....

Entity Framework Notes (i)

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.