The Modelfirst and Dbfirst of EF in layman's

Source: Internet
Author: User

In the Last post, the small part of the main simple introduction of some of the basic knowledge of EF, which, small dragonfly water of Modelfirst and Dbfirst,modelfirst first design entities, and then based on the model database generation, Dbfirst based on the database model, Two directions are available, two directions can be updated with each other, such as new entities added, you can build the database based on the model, if you add new fields in the database, we can update the model from the database. Before we introduce Modelfirst and Dbfirst, let's address two questions, the relationship between EF and LINQ to SQL, and why LINQ to SQL and EF are used.

the relationship between EF and LINQ to SQL

LINQ to SQL is an embodiment of the Microsoft ORM Idea, and EF is also a materialization of it, so what is the difference between these two products? LINQ to SQL is a lightweight framework implemented by ORM, and EF is a heavyweight framework; one important difference between LINQ to SQL and EF is that LINQ to SQL can only be targeted at SQL Server databases, and EF is able to pin many databases (Oracle, SQL Server, etc.), that is, EF is cross-database, do not underestimate this, in the actual development, very practical, to give a simple small example, Also remember we knocked vb.net version of the computer room charge system, which involves the data access layer, if for some reason, we change the database, then we need to rewrite the data access layer, if we in the creation of computer room charge system This project, the use of LINQ to SQL, Changing the database LINQ to SQL Framework requires a lot of reworking, and if you use the EF framework, then we just need to change the configuration file in it so that we don't need to modify the code in the program.

why use LINQ to SQL and EF

This problem, but also related to our D layer, remember to knock the computer room charge system, we will take out a SqlHelper class, this class to implement the addition and deletion of the database, and then, we re-create the corresponding D-layer class, the functions of these methods are actually similar, the only difference is SQL, From here we can see that the problem of our D layer, that is, we repeatedly write some unnecessary classes or methods, to solve this method requires a gradual abstraction, abstraction of common things, such as: DataTable loaded into the entity set, the operation of the database of several kinds of methods (note its parameters), and then the integration , this is roughly the prototype of the ORM idea that we belong to, of course, the things that are mentioned above, the LINQ to SQL or EF frameworks have helped us, we just need to use the methods they provide, and from here we can see that if we use these frameworks, When programmers are programming, we hardly need to manage the D-layer, just focus on the implementation of the business.

Next, the small part to introduce briefly Modelfirst,modelfirst first design the entity, and then build the database according to the model, as shown in,

We can then right-click on the left side of the diagram to add the entity, add a scalar attribute, and append the association. Next, we can build the database based on the entity above, as shown in:

The generated code is as follows:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;"  >------------------------------------------------------Entity Designer DDL Script for SQL Server 2005, Azure------------------------------------------------------Date created:01/28/2015 15:43:19--Generated from EDMX FILE:C:\USERS\FLOWER\DESKTOP\EFDEMO\MODELFIRSTDEMO\DATAMODEL.EDMX--------------------------------------------- -------SET QUOTED_IDENTIFIER OFF; Gouse [MODELFIRSTDEMODB2]; GOif schema_id (n ' dbo ') is NULL EXECUTE (n ' CREATE SCHEMA [dbo] '); GO------------------------------------------------------dropping existing FOREIGN KEY constraints----------------- -----------------------------------IF object_id (N ' [dbo].[ Fk_customerorder] ', ' F ') is not NULL ALTER TABLE [dbo]. [Order] DROP CONSTRAINT [Fk_customerorder]; GO------------------------------------------------------dropping existing tables-------------------------------- --------------------IF object_id (N ' [dbo].[ Customer] ', ' U ') is not NULL DROP TABLE [dbo]. [Customer]; GOif object_id (N ' [dbo].[ Order] ', ' U ') is not NULL DROP TABLE [dbo]. [Order]; GO------------------------------------------------------Creating all tables------------------------------------- -----------------Creating table ' Customer ' CREATE table [dbo]. [Customer] ([Id] int IDENTITY () not NULL, [cusname] nvarchar (+) null, [subtime] datetime NOT NULL, [Delflag] Small int NULL); go--Creating table ' Order ' CREATE table [dbo]. [Order] ([Id] int IDENTITY () not NULL, [ordercontent] nvarchar (max) isn't null, [CustomerId] int not null); go--Creating table ' UserInfo ' CREATE table [dbo]. [UserInfo] ([Id] int IDENTITY () not NULL); GO------------------------------------------------------Creating all PRIMARY KEY constraints---------------------- --------------------------------Creating primary key on [Id] in table ' Customer ' ALTER table [dbo]. [Customer] ADD CONSTRAINT [Pk_customer] PRIMARY KEY CLUSTERED ([Id] ASC); go--CreatinG primary key on [Id] in table ' Order ' ALTER table [dbo]. [Order] ADD CONSTRAINT [Pk_order] PRIMARY KEY CLUSTERED ([Id] ASC); go--Creating primary key on [Id] in table ' UserInfo ' ALTER table [dbo]. [UserInfo] ADD CONSTRAINT [Pk_userinfo] PRIMARY KEY CLUSTERED ([Id] ASC); GO------------------------------------------------------Creating all FOREIGN KEY constraints---------------------- --------------------------------Creating foreign key on [CustomerId] in table ' Order ' ALTER table [dbo]. [Order] ADD CONSTRAINT [Fk_customerorder] FOREIGN KEY ([CustomerId]) REFERENCES [dbo].        [Customer]  ([Id]) on the DELETE no ACTION on UPDATE no action;--Creating non-clustered index for FOREIGN KEY ' Fk_customerorder ' CREATE INDEX [Ix_fk_customerorder]on [dbo].    [Order] ([CustomerId]); GO------------------------------------------------------Script has ended---------------------------------------- ------------</span></span>
then let's look at a concrete example where the insert operation code for the Modelfirst associated entity is as follows:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace modelfirstdemo{class Program {static void Main (string[] args) {Datamodelcontai            NER db = new Datamodelcontainer ();            Insert Operation #region Model first associated entity customer customer = new Customer (); Customer.            Cusname = "hehe"; Customer.            Delflag = 0; Customer.            Subtime = DateTime.Now;            Order order = New Order (); Order.            Ordercontent = "Flower"; Assigns a value//order to a navigation property.            Customerid= customer.id; Order.            Customer = customer;            Order Order2 = New Order (); Order2.             Ordercontent= "Flower2"; Order.            Customerid= customer.id; Order2.            Customer = customer; Db.            Customer.add (customer); Db.            Order.add (order); Db.         Order.add (ORDER2);   Db.            SaveChanges (); #endregion}}}</span></span>
Next, let's take a look at Dbfirst, based on the database generation model, let's take a look at the following code:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;"  >using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;    Using System.Data; Namespace EF. Entityframeworkdemo {class Program {static void Main (string[] args) {#region              Add entity////Create context object//dbfirstentities Dbfirst = new Dbfirstentities ();              Operation entity//t_customer Customer = new T_customer (); Customer.              Cusname = "newly added user";              Attached to the context//dbfirst.t_customer.addobject (Customer);              Save//dbfirst.savechanges (); #endregion #region Delete Entity////1, create context object//dbfirstentities Dbfirst = new Dbfirstentit              IES ();              2. Create entity//t_customer Customer = new T_customer ();              Customer.id = 9; 3, the entity is attached to the context for management//dbfirst.t_custoMer.              Attach (customer);              Modify the state of the entity//dbfirst.objectstatemanager.changeobjectstate (Customer, entitystate.deleted);              4, the context Operation database//dbfirst.savechanges (); #endregion #region Modify the entity////1, create a context object that accesses the database//dbfirstentities Dbfirst = new Dbfirs              Tentities ();              2, modify the object//t_customer Customer = new T_customer ();              Customer.id = 4; Customer.              Cusname = "User 4_ modified 2";              3, attached to the database//dbfirst.t_customer.addobject (Customer);              Modify Object state//dbfirst.objectstatemanager.changeobjectstate (customer, entitystate.modified);              4, the Context Update database//dbfirst.savechanges ();                #endregion #region Query Dbfirstentities dbfirst = new Dbfirstentities (); foreach (var item in Dbfirst.t_customer) {Console.WriteLine (string. FoRmat ("id:{0} Name:{1}", Item.id,item.              Cusname)); #region LINQ expression T_customer cs = (from Customer in dbfirst.t_customer where customer.id = = 2 SE Lect customer).              Singleordefault (); Console.WriteLine ("Id:{0} Name:{1}", Cs.id,cs.              Cusname);          #endregion #endregion Console.readkey (); }}} </span></span>

Modelfirst and Dbfirst two ways, can achieve the effect we want to achieve the same purpose, two methods can be updated with each other, the last small part of the simple to introduce a lazy load, delay loading can also be called on-demand loading, can be divided into two aspects to understand, on the one hand, that the data is not needed, You don't need to load it right now, but you can postpone it until you use it, and on the other hand you don't know if it will be needed, so don't load it for the moment, and then load it until you're sure. Lazy loading is an important data access feature that effectively reduces the interaction with the data source (note that the interaction mentioned here is not the number of interactions, but the amount of data being interacted with), thereby improving program performance. There are two types of lazy loading in EF, as shown in the following code:

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace modelfirstdemo{class Program {static void Main (string[] args) {Datamodelcontai            NER db = new Datamodelcontainer ();            Insert Operation #region Model first associated entity customer customer = new Customer (); Customer.            Cusname = "hehe"; Customer.            Delflag = 0; Customer.            Subtime = DateTime.Now;            Order order = New Order (); Order.            Ordercontent = "Flower"; Assigns a value order to the navigation property.            Customerid= customer.id; Order.            Customer = customer;            Order Order2 = New Order (); Order2.             Ordercontent= "Flower2"; Order.            Customerid= customer.id; Order2.            Customer = customer; Db.            Customer.add (customer); Db.            Order.add (order); Db.           Order.add (ORDER2); Db.            SaveChanges (); #endregion #region Add another way to summarize queries: lambda expression lambda expressions and the Il code that is generated after the compile phase of a LINQ expression is the same as var item = (from C in db.) Customer where c.id = = 2 Select c).            FirstOrDefault ();            list<string> list = new list<string> (); List. FindAll () function<customer,bool> Lambda in the way var ITEMLAMBDA = db. Customer.where<customer> (c=>c.id==1).            FirstOrDefault ();            Console.WriteLine (Itemlambda.cusname); #endregion #region Delay the first data that was found using LINQ or lambda expressions, only to go back to the real query data when used. var items = from C in Db.            Customer where C.id < select C; foreach (var customer in items) {Console.WriteLine (Customer.            ID); } IQueryable foreach (var customer in items) {CONSOLE.WRIteline (Customer.            ID); } #endregion #region the second delay load var customers = from C in db.            Customer Select C; foreach (Var cus in Customers) {Console.WriteLine (cus.                Id + "------"); foreach (var order in Cus. Order) {Console.WriteLine (order.                ID);            } Console.WriteLine ("------");                        #endregion #region Query the data for a partial column only queries the data for some of the columns in the table var items = from C in Customer Where C.id < select new {Id = c.id, Cusname = c.cusname, Count = 0, Orde            Rcount = C.order.count ()}; foreach (var item in items) {Console.WriteLine (item.            Cusname + "------" + item.ordercount); } #endregion the difference between the #region Iquerable interface and other collections var items = (from C in DB.                     Order    Where C.id < 2 select c).            ToList (); foreach (var order in items) {Console.WriteLine (order.            ID);        } #endregion Console.readkey (); }}}</span></span>
message : The blog, the small part mainly introduces some of the basic knowledge of EF, from three aspects of the EF in detail, the first aspect: the relationship between EF and LINQ to SQL and why to use EF and LINQ to SQL, the second aspect, introduced the M Odelfirst and Dbfirst, finally introduced a delay loading, the relevant knowledge of EF, small series just contact, understanding or very shallow, there are different views of the small partners can discuss the exchange oh, often think, if not because of fate, if not because of the project to accept what MVC, EF, LINQ, and so on, not so quick to start contact, in the course of the project to learn, and then to learn the knowledge to apply to the project, bright Bang Bang, file management projects, not to be continued ...

The Modelfirst and Dbfirst of EF in layman's

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.