12/06/2011

Entity Framework Batch Update and Future Queries

Entity Framework Extended Library

Pasted from <http://weblogs.asp.net/pwelter34/archive/2011/11/29/entity-framework-batch-update-and-future-queries.aspx>

 
 

A library the extends the functionality of Entity Framework.

Features

  • Batch Update and Delete
  • Future Queries
  • Audit Log

Project Package and Source

NuGet Package:

PM> Install-Package EntityFramework.Extended

Batch Update and Delete

A current limitations of the Entity Framework is that in order to update or delete an entity you have to first retrieve it into memory. Now in most scenarios this is just fine. There are however some senerios where performance would suffer. Also, for single deletes, the object must be retrieved before it can be deleted requiring two calls to the database. Batch update and delete eliminates the need to retrieve and load an entity before modifying it.

Deleting

//delete all users where FirstName matches

context.Users.Delete(u => u.FirstName == "firstname");

 
 

Update

//update all tasks with status of 1 to status of 2

context.Tasks.Update(

t => t.StatusId == 1,

t => new Task {StatusId = 2});

 
 

//example of using an IQueryable as the filter for the update

var users = context.Users

.Where(u => u.FirstName == "firstname");

 
 

context.Users.Update(

users,

u => new User {FirstName = "newfirstname"});

 
 

Future Queries

Build up a list of queries for the data that you need and the first time any of the results are accessed, all the data will retrieved in one round trip to the database server. Reducing the number of trips to the database is a great. Using this feature is as simple as appending .Future() to the end of your queries. To use the Future Queries, make sure to import the EntityFramework.Extensions namespace.

Future queries are created with the following extension methods...

  • Future()
  • FutureFirstOrDefault()
  • FutureCount()

Sample

// build up queries

var q1 = db.Users

.Where(t => t.EmailAddress == "one@test.com")

.Future();

 
 

var q2 = db.Tasks

.Where(t => t.Summary == "Test")

.Future();

 
 

// this triggers the loading of all the future queries

var users = q1.ToList();

In the example above, there are 2 queries built up, as soon as one of the queries is enumerated, it triggers the batch load of both queries.

// base query

var q = db.Tasks.Where(t => t.Priority == 2);

// get total count

var q1 = q.FutureCount();

// get page

var q2 = q.Skip(pageIndex).Take(pageSize).Future();

 
 

// triggers execute as a batch

int total = q1.Value;

var tasks = q2.ToList();

In this example, we have a common senerio where you want to page a list of tasks. In order for the GUI to setup the paging control, you need a total count. With Future, we can batch together the queries to get all the data in one database call.

Future queries work by creating the appropriate IFutureQuery object that keeps the IQuerable. The IFutureQuery object is then stored in IFutureContext.FutureQueries list. Then, when one of the IFutureQuery objects is enumerated, it calls back to IFutureContext.ExecuteFutureQueries() via the LoadAction delegate. ExecuteFutureQueries builds a batch query from all the stored IFutureQuery objects. Finally, all the IFutureQuery objects are updated with the results from the query.

Audit Log

The Audit Log feature will capture the changes to entities anytime they are submitted to the database. The Audit Log captures only the entities that are changed and only the properties on those entities that were changed. The before and after values are recorded. AuditLogger.LastAudit is where this information is held and there is a ToXml() method that makes it easy to turn the AuditLog into xml for easy storage.

The AuditLog can be customized via attributes on the entities or via a Fluent Configuration API.

Fluent Configuration

// config audit when your application is starting up...

var auditConfiguration = AuditConfiguration.Default;

 
 

auditConfiguration.IncludeRelationships = true;

auditConfiguration.LoadRelationships = true;

auditConfiguration.DefaultAuditable = true;

 
 

// customize the audit for Task entity

auditConfiguration.IsAuditable<Task>()

.NotAudited(t => t.TaskExtended)

.FormatWith(t => t.Status, v => FormatStatus(v));

 
 

// set the display member when status is a foreign key

auditConfiguration.IsAuditable<Status>()

.DisplayMember(t => t.Name);

Create an Audit Log

var db = new TrackerContext();

var audit = db.BeginAudit();

 
 

// make some updates ...

 
 

db.SaveChanges();

var log = audit.LastLog;

 
 

Published Tuesday, November 29, 2011 10:24 AM by pwelter34

Filed under: .net, Entity Framework

3/07/2011

Creating S.M.A.R.T. Goals

Blogged from Creating S.M.A.R.T. Goals




src="If%20a%20man%20knows%20not%20what%20harbor%20he%20seeks_files/image001.gif"
alt="Description: Self Improvement Articles">



lang=EN-US style='font-size:12.0pt;font-family:"Lucida Handwriting"'>If a man
knows not what harbor he seeks,

any wind is the right wind.

-Senecastyle='font-size:12.0pt;font-family:"Times New Roman","serif"'>



width=386 height=5
src="If%20a%20man%20knows%20not%20what%20harbor%20he%20seeks_files/image002.png"
alt="Description: self improvement articles">



Creating S.M.A.R.T. Goalslang=EN-US style='font-size:12.0pt;font-family:"Times New Roman","serif"'>



style='font-size:12.0pt;font-family:"Times New Roman","serif"'>              
              
              
              
    
Specific

              
              
              
              
    
Measurable


              
              
              
              
    
Attainable


              
              
              
              
    
Realistic


              
              
              
              
    
Timely



src="If%20a%20man%20knows%20not%20what%20harbor%20he%20seeks_files/image003.gif"
alt="Description: Smart Goals">



Specific style='font-size:12.0pt;font-family:"Times New Roman","serif"'>- A specific
goal has a much greater chance of being accomplished than a general goal. To
set a specific goal you must answer the six "W" questions:



style='font-size:12.0pt;font-family:"Times New Roman","serif"'>*Who:      Who
is involved?

*What:     What do I want to accomplish?

*Where:    Identify a location.

*When:     Establish a time frame.

*Which:    Identify requirements and constraints.

*Why:      Specific reasons, purpose or benefits
of accomplishing the goal.



style='font-size:13.5pt;font-family:"Times New Roman","serif"'>EXAMPLE:lang=EN-US style='font-size:12.0pt;font-family:"Times New Roman","serif"'>   
A general goal would be, "Get in shape." But a specific goal would
say, "Join a health club and workout 3 days a week."



src="If%20a%20man%20knows%20not%20what%20harbor%20he%20seeks_files/image003.gif"
alt="Description: Smart Goals">



Measurable style='font-size:12.0pt;font-family:"Times New Roman","serif"'>- Establish
concrete criteria for measuring progress toward the attainment of each goal you
set. When you measure your progress, you stay on track, reach your target
dates, and experience the exhilaration of achievement that spurs you on to
continued effort required to reach your goal.



style='font-size:12.0pt;font-family:"Times New Roman","serif"'>To determine if
your goal is measurable, ask questions such as......How much? How many? How
will I know when it is accomplished?



src="If%20a%20man%20knows%20not%20what%20harbor%20he%20seeks_files/image003.gif"
alt="Description: Smart Goals">



Attainablestyle='font-size:12.0pt;font-family:"Times New Roman","serif"'> - When you
identify goals that are most important to you, you begin to figure out ways you
can make them come true. You develop the attitudes, abilities, skills, and
financial capacity to reach them. You begin seeing previously overlooked opportunities
to bring yourself closer to the achievement of your goals.



style='font-size:12.0pt;font-family:"Times New Roman","serif"'>You can attain
most any goal you set when you plan your steps wisely and establish a time
frame that allows you to carry out those steps. Goals that may have seemed far
away and out of reach eventually move closer and become attainable, not because
your goals shrink, but because you grow and expand to match them. When you list
your goals you build your self-image. You see yourself as worthy of these
goals, and develop the traits and personality that allow you to possess them.



src="If%20a%20man%20knows%20not%20what%20harbor%20he%20seeks_files/image003.gif"
alt="Description: Smart Goals">



Realisticstyle='font-size:12.0pt;font-family:"Times New Roman","serif"'> - To be
realistic, a goal must represent an objective toward which you are both willing
and able to work. A goal can be both high and realistic; you are the
only one who can decide just how high your goal should be. But be sure that
every goal represents substantial progress. A high goal is frequently easier to
reach than a low one because a low goal exerts low motivational force. Some of
the hardest jobs you ever accomplished actually seem easy simply because they
were a labor of love.



style='font-size:12.0pt;font-family:"Times New Roman","serif"'>Your goal is
probably realistic if you truly believe that it can be accomplished.
Additional ways to know if your goal is realistic is to determine if you have
accomplished anything similar in the past or ask yourself what conditions would
have to exist to accomplish this goal.



src="If%20a%20man%20knows%20not%20what%20harbor%20he%20seeks_files/image003.gif"
alt="Description: Smart Goals">



Timely - A goal should be grounded
within a time frame. With no time frame tied to it there's no sense of urgency.
If you want to lose 10 lbs, when do you want to lose it by? "Someday"
won't work. But if you anchor it within a timeframe, "by May 1st",
then you've set your unconscious mind into motion to begin working on the goal.



style='font-size:13.5pt;font-family:"Times New Roman","serif";color:red'>Tlang=EN-US style='font-size:12.0pt;font-family:"Times New Roman","serif"'> can
also stand for Tangible - A goal is tangible when you can experience it
with one of the senses, that is, taste, touch, smell, sight or hearing. When
your goal is tangible you have a better chance of making it specific and
measurable and thus attainable.



lang=EN-US style='font-size:12.0pt;font-family:"Times New Roman","serif"'> 



Please also see



style='font-size:18.0pt;font-family:"Times New Roman","serif"'>href="http://www.topachievement.com/">Goal Setting - Powerful
Written Goals In 7 Easy Steps!



lang=EN-US style='font-size:13.5pt;font-family:"Times New Roman","serif"'>by
Top Achievement founder Gene Donohue.



lang=EN-US style='font-size:12.0pt;font-family:"Times New Roman","serif"'> 



style='font-size:13.5pt'>Return To Articles Page



style='font-size:12.0pt;font-family:"Times New Roman","serif"'> 



 



2/04/2011

SqlConnection Connection String Parameter Keywords & Values

(Copied from Wayne Allen’s blog,
http://weblogs.asp.net/wallen/archive/2005/03/22/395496.aspx.)


Name



Default




Description



Application Name


 


The name of the application, or '.Net SqlClient Data Provider' if no application name is provided.


AttachDBFilename
-or-
extended properties
-or-
Initial File Name


 


The name of the primary file, including the full path name, of an attachable database. If this setting is specified, the
Initial Catalog setting must also be specified.

The database name must be specified with the keyword 'database'.

Example:
Data Source=.; Initial Catalog=; Integrated Security=true;AttachDBFileName=c:\MyFolder\MyDb.mdf 

Update:

You can use the following syntax to attach a database that lives in your "Data" directory:

AttachDBFileName=|DataDirectory|MyDb.mdf 


Connect Timeout
-or-
Connection Timeout


15


The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.


Current Language


 


The SQL Server Language record name.


Data Source
-or-
Server
-or-
Address
-or-
Addr
-or-
Network Address


 


The name or network address of the instance of SQL Server to which to connect.


Encrypt


'false'


When
true, SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed. Recognized values are
true, false, yes, and no.


Initial Catalog
-or-
Database


 


The name of the database.


Integrated Security
-or-
Trusted_Connection


'false'


When
false, User ID and Password are specified in the connection. When
true, the current Windows account credentials are used for authentication.



Recognized values are
true, false, yes, no, and sspi (strongly recommended), which is equivalent to
true.


Network Library
-or-
Net


'dbmssocn'


The network library used to establish a connection to an instance of SQL Server. Supported values include dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmslpcn (Shared Memory) and dbmsspxn (IPX/SPX), and dbmssocn (TCP/IP).



The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used.


Packet Size


8192


Size in bytes of the network packets used to communicate with an instance of SQL Server.


Password
-or-
Pwd


 


The password for the SQL Server account logging on (Not recommended. To maintain a high level of security, it is strongly recommended that you use the Integrated Security or Trusted_Connection keyword instead.).


Persist Security Info


'false'


When set to
false or no (strongly recommended), security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password. Recognized values are
true, false, yes, and no.


User ID


 


The SQL Server login account (Not recommended. To maintain a high level of security, it is strongly recommended that you use the Integrated Security or Trusted_Connection keyword instead.).


Workstation ID


the local computer name


The name of the workstation connecting to SQL Server.


Connection Lifetime


0


When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by
Connection Lifetime. This is useful in clustered configurations to force load balancing between a running server and a server just brought online.



A value of zero (0) causes pooled connections to have the maximum connection timeout.


Connection Reset


'true'


Determines whether the database connection is reset when being drawn from the pool. For Microsoft SQL Server version 7.0, setting to
false avoids making an additional server round trip when obtaining a connection, but you must be aware that the connection state, such as database context, is not being reset.


Enlist


'true'


When
true, the pooler automatically enlists the connection in the creation thread's current transaction context. Recognized values are
true, false, yes, and no.


Max Pool Size


100


The maximum number of connections allowed in the pool.


Min Pool Size


0


The minimum number of connections allowed in the pool.


Pooling


'true'


When
true, the SQLConnection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool. Recognized values are
true, false, yes, and no.