您的位置:首页 > 数据库

ADO.Net Linq to SQL and Linq to Entities Note

2012-08-27 00:20 351 查看
**Linq to SQL

Database Context

-Log

-dc.Log=Console.Out;

-dc.Log.Flush();

-FinishingCRUD

-dc.SubmitChanges()

-StoreProcedure

-resulttype auto-generate or use existing one

-EagerLoading vs. Lazy Loading

-EagerLoading vs. Lazy Loading

-Eagerloading is also known as pre-fetch loading (default)

-TrackChanges and Cache Objects (DataContext)

-TheLife Cycle of an Entity (LINQ to SQL objects always have a state)

-Untracked

-Unchanged

-PossiblyModified

-ToBeInserted

-ToBeUpdated

-ToBeDeleted

-Deleted

-Operation

-Add

Anew object you instantiate yourself is unknown to DataContext and is inUntracked state

e.g.:ctx.Employees.InsertOnSubmit(employee);

-Edit

WhenLINQ to SQL creates a new object, the object is in Unchanged state. If youmodify the object, the DataContext object will change the state of the objectto the ToBeUpdated state.

**Howdoes the DataContext object know when you change your object? Changenotifications are accomplished through the PropertyChanging event that’s inproperty setters. When DataContext receives a change notification,
it creates acopy of the object and changes its state to ToBeUpdated.

-Delete

e.g.:ctx.Employees.DeleteOnSubmit(employee);

LINQto SQL does not support or recognize cascade-delete operations

Solution

-setthe ON DELETE CASCADE rule in the foreign-key constraint in the database

-writeyour own code

-UsingDataContext to Submit Changes

-ctx.SubmitChanges();

**Afteryou use LINQ to SQL to retrieve data, you might make many changes to theobjects, but remember that these changes are made only to your in-memoryobjects. No changes are sent to the database until you call the SubmitChangesmethod
on the DataContext object.

**Linq to Entities

-de.SaveChanges()

-CodeFirst Model vs. Database First Model

-CodeFirst:create your conceptual model before you create the database

-DatabaseFirst

-Managingyour Database Connection and Context Using ObjectContext

-StoringInformation about Objects and Their State

-Thechangetracking information for the returned objects is stored inObjectStateEntry objects, which ObjectContext creates for each retrieved orattached object.

-EntityState Enumeration

-Added

-Deleted

-Modified

-Detached

-Unchanged

-LazyLoading vs. Explicit Loading vs. Eager Loading

-Lazyloading is also known as just-in-time loading, lazy initialization, on-demandloading, and deferred loading (Default)

-Touse eager loading, use the Include method to include the order detail objectswhen running the query for the order

e.g.:db.Orders.Include("Order_Details")

-Touse explicit loading, use the Load method to load the order detail objectsbefore executing

the ToList method

e.g.:

varorder = db.Orders.Where(o => o.CustomerID == "ALFKI").First();

order.Order_Details.Load();

gv.DataSource= order.Order_Details.ToList();

-ImplementingInheritance in the Entity Framework

-Tableper Class Hierarchy (TPH)

-Single Table Inheritance. all concrete types in the inheritance hierarchy arestored on one table.

-thesimplest and easiest to implement

-Tableper Type (TPT)

-themost efficient

-Witha one-to-one mapping of type to table

-Tableper Concrete Class (TPC)

-POCOEntities

-EntitySQL

-UsingObjectContext to Submit Changes to the Database

-Edit

-e.g.:db.SaveChanges()

-TheEntity Data Model Generator creates classes in which each property containsOnPropertyChanging and OnPropertyChanged events. You can extend the entityclass to add code that subscribes to these events as
needed. Any change to ascalar property causes the entity’s EntityState property to be Modified.

-Add

-e.g:db.Employees.AddObject(emp);

-AttachingEntities to an ObjectContext

-e.g:db.Detach(customer);

db.Customers.Attach(customer);

-Whenworking with POCO, you must call the DetectChanges method on the ObjectContextto attach the POCO entity to the ObjectContext. Be sure to call DetectChangesprior to calling SaveChanges.

-Delete

-e.g:db.Order_Details.DeleteObject(itemToDelete);

-CascadingDeletes

-Youcan also set up a delete rule in your EDMX file

**It’simportant to note that a cascading delete in the Entity Framework works only ifthe dependent entity objects are loaded. This can be accomplished using theInclude or Load methods.

-EF3.5ObjectContext

-keepstate for each entity, manage entities

-eachentity inherit EntityObject

-EF4

-POCO

-Solution1: POCO Snapshot 4.0,

-LazyLoading:

-expilcityindicate since only context know lazy loading:context.LoadProperty(person,p=>p.FavoriteBeer);

-virtualproperty: public virtual ICollection<FavoriteBeer>FavoriteBeers{get;set;}

-TrackChanges

-context.DetectChange();//

-**context.SaveChanges()in EF4 help you call DectectChange() for you

-Solution2: Dynamic Runtime Proxy 4.0

-Makeall model property mark as "virtual", then dynamic entity object with_changetrack etc

-Rulesfor Proxy Notification

-1.allentity properties shalt be virtual

-2.shaltuse IConnection<T>

-3.***Creationshall be done with

OjbectContext.CreateObject<T>

-4.Classesshall not be sealed

-5.Navigationproperties shall not be sealed

-6.Classesshould not be abstract

-7.Classesshould have a parameter-less contructor

-8.Propertiescan only has {get;set;} cannot put any logic inside

Disconnect Environment

Change Tracking Across Tiers

-WebService

-EntiyState Entry gone, Original Property Value gone

-Contextalso not seariable

-WebPage Post Back

-Context is new

Solution

-1.WCF& Self-Tracking Entity

-ApplyChanges()

-Cons: client need to know Self-Tracking, and do it then send to server

-2.WCFData Service

-createa model and configuration

-restful API

-3.WCF

-context.ObjectStateManger

-AddEntityStore

-EditEntityStore

-DeleteEntityStore

-DeleteRelationStore

-context.ObjectStateManger.ChangeObjectState(cust,System.Data.EntityState.Modified)

-UnChanged,Modified, Add, Delete
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: