How To improve Entity Framework Performance

it is mandatory to know about performance of it. These are right up to a certain point as LINQ comes with its own penalties. There are some tips and tricks that we should keep in mind while desiging and query database using entity framework

Here is a list of some tips you would like to know.

1) Avoid to put all the DB Objects into One Single Entity Model

If we have many database objects that are not connected to one another or these(log tables, objects used by batch processes,etc.) are not used at all. Hence these objects are consuming space in the memory and cause performance degrades. So try to make separate entity models of related database objects

2)Disable change tracking for entity if not needed

if you need to retrieve the data only for reading purpose then no need of object tracking. disable object tracking by using MergeOption as below

NorthwindDataContext context = new NorthwindDataContext() context.tblCities.MergeOption = MergeOption.NoTracking;

3)Use Compiled Query wherever needed

Make a query to compiled query if it is frequently used to fetch records from the database. This query is slow in first time but after that it boost the performance significantly.

The following example compiles and then invokes a query that accepts a Decimal input parameter and returns a sequence of orders where the total due is greater than or equal to $200.00:

static readonly Func<AdventureWorksEntities, Decimal, IQueryable> s_compiledQuery2 = 
    CompiledQuery.Compile<AdventureWorksEntities, Decimal, IQueryable>(
            (ctx, total) => from order in ctx.SalesOrderHeaders
                            where order.TotalDue >= total
                            select order);

static void CompiledQuery2()
{            
    using (AdventureWorksEntities context = new AdventureWorksEntities())
    {
        Decimal totalDue = 200.00M;

        IQueryable orders = s_compiledQuery2.Invoke(context, totalDue);

        foreach (SalesOrderHeader order in orders)
        {
            Console.WriteLine("ID: {0}  Order date: {1} Total due: {2}",
                order.SalesOrderID,
                order.OrderDate,
                order.TotalDue);
        }
    }            
}

4)Retrieve only required number of records

retrieve only required no of records to improve performance. This can achieved by using Take,While and Skip methods.

4)Avoid using Views

Views degrade the LINQ query performance costly. These are slow in performance and impact the performance greatly. So avoid using views in LINQ to Entities

 

Summery  :

this is some tips to help you improves the performance i hop you enjoy reading  this article and i hop it help you to make your query on better way

Advertisements

Stored procedure vs Sql function

In SQL Server functions and stored procedure are two different types of entities and every one have its  own features and limitation , for that if we now what are the major  differences between them we can write query on efficient way

I believe that they are both different things they cannot be compared. I can say, it will be like comparing apples and oranges. Each has its own unique use .

This article briefly explain What is a Stored Procedure and what is a Function in SQL Server? It also explains the working and major differences between function and stored procedure in SQL server.

Definition 

Stored Procedure

A Stored Procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a Stored Procedure and then just call the Stored Procedure to execute the SQL code

User Defined Functions

Like functions in programming languages, SQL Server User Defined Functions are routines that accept parameters, perform an action such as a complex calculation, and returns the result of that action as a value. The return value can either be a single scalar value or a result set.

Types 

Types of Functions in SQL Server

There are two types of functions in SQL which are given as following:

Types of Functions in SQL Server

There are two types of functions in SQL which are given as following:

  1. Built-in Functions :The built-in functions are facility provided by the SQL Server to perform several tasks. These functions can also used in T-SQL statements. The built-in function accesses the information from SQL Server system tables without accessing the system tables directly. The built-in functions return value either scalar or table data types.
  2. User-Defined Function : The user defined functions or subroutines performs actions like complex calculation and return results. These functions are made up of one or more T-SQL statements and can be used as to encapsulate the codes for reuse.User-defined functions are created using the Create Function Like :

CREATE FUNCTION function_name( parameter_name  type , parameter_name Type …  ) RETURNS return_data_type [ WITH [ ,..n ] ] [ AS ] BEGIN function_body
RETURN scalar_expression
END

Types of User Defined Functions

  1. Scalar user defined functionA Scalar user defined function can accept from 0 to many input parameters and a single value will be returned as a result. A scalar UDF can return the results in the form of int, char, and varchar etc..
  2. Inline table valued user defined function: :An inline table-valued user defined function produces data type table variables and its value can be derived from the single select statement. In this function there is no need of begin and end blocks, no need to specify the variables of the tables and not allowed duplicate column names etc.. After declaration of function we can use it as like this.

    SELECT * FROM Fn_GetCityByCountryID(285)

    3. Multi Statement table valued user defined function:This is a different type of function which may contain multiple T-SQL statements. When you want to create a multi statement table valued function then you must need to define the table structure. We can use it in the FROM clause of a T-SQL command.

    After declaration of multi statements table valued user defined function as like this.

    SELECT * FROM  Fn_GetCustomerByCity(285) SELECT * FROM Fn_GetCustomerByCity(1)

Benefits of user defined Functions 

    • They allow modular programming: You can create the function once, store it in the database, and call it any number of times in your program. User Defined Functions can be modified independently of the program source code.
    • They allow faster execution: Similar to Stored Procedures, Transact-SQL User Defined Functions reduce the compilation cost of Transact-SQL code by caching the plans and reusing them for repeated executions. This means the user-defined function does not need to be reparsed and reoptimized with each use resulting in much faster execution times. CLR functions offer significant performance advantage over Transact-SQL functions for computational tasks, string manipulation, and business logic. Transact-SQL functions are better suited for data-access intensive logic.
    • They can reduce network traffic: An operation that filters data based on some complex constraint that cannot be expressed in a single scalar expression can be expressed as a function. The function can then invoked in the WHERE clause to reduce the number or rows sent to the client.

Limitations of User Defined Functions:

  • Unable to modify the databases states.
  • Does not contains OUTPUT INTO clause.
  • A UDF can’t support TRY.. ..CATCH and SET statements.
  • Unable to call a stored procedure (SP), but can call an extended stored procedure(ESP).
  • Can not use dynamic SQL or temp tables, while table variables may use.
  • XML clause is not allowed in user defined functions.

Types of stored Procedure 

there are several four type of stored procedures in SQL. Here I have explained broadly each of them:

  1. User-defined Stored Procedure
  2. System-defined Stored Procedure:
  3. Temporary Stored Procedure:The temporary stored procedure means that it is present in temporary session. This type of stored procedures is prefixed with a hash sign (# ). Where one sign shows that it is present in the temporary session while if it used with double hash sign, this means that the procedure is present globally.
  4. Extended Stored Procedure:Extended stored procedures exist because they allow you to do things that you cannot do with T-SQL like running a DOS command (xp_cmdshell). These stored procedures are routines resides in DLLs which are very similar to the regular stored procedures. The extended stored procedures receives the parameters and return resultant value via SQL Server’s Open Data Services API.
    • Benefits of user Stored Procedures  

      Precompiled execution: SQL Server compiles each Stored Procedure once and then re utilizes the execution plan. This results in tremendous performance boosts when Stored Procedures are called repeatedly.

    • Reduced client/server traffic: If network bandwidth is a concern in your environment then you’ll be happy to learn that Stored Procedures can reduce long SQL queries to a single line that is transmitted over the wire.
    • Efficient reuse of code and programming abstraction: Stored Procedures can be used by multiple users and client programs. If you utilize them in a planned manner then you’ll find the development cycle requires less time.
    • Enhanced security controls: You can grant users permission to execute a Stored Procedure independently of underlying table permissions. 

      Limitations of stored procedure:

      There are also some limitations of stored procedure in SQL which are discussed below:

      • Stored procedure may or not return values.
      • A stored procedure can’t be utilized in selective statements.

spvsfunction

​When do you use structs vs classes?

when do we use a struct versus a class? So in C#,
as well as some other object-oriented programming languages,
we have the ability to create a structure in the code or we have
the ability to create a class in the code. And some folks who
are new to dealing with object-oriented programing, or even C#
the ability to create a class in the code. And some folks who
are new to dealing with object-oriented programing, or even C#
in general, are kind of saying, well, a struct in class almost
look the same, why would I use a struct over a class or why would
I use a class over a struct?

https://mva.microsoft.com/en-US/training-courses-embed/twenty-c-questions-answered-8298/-When-do-you-use-structs-vs-classes–m0lBxQYy_504984382

Scoping your Solution Explorer in Visual Studio

You may find this tip very handy and useful in case you are dealing with a large solution with several projects in Visual studio.  We don’t work across the solution / all projects together. and you need to keep focus  to one project in this solution

 

all what you need to do is  :

    right click the project  and click   ” Scope to This

    

scope this

 

and click on the “Back”  , “Forward” or Home button to navigate across.

 

scope this 3

 

Similarly you can scoped multiple projects

 

 

 

Along withScope to This” feature you can also leverage “New Solution Explorer viewto create  new instances of Solution Explorer.

With this you will have two different solution explorer as shown in below screenshot.

 

scope this 2

 

How to check whether Wi-Fi Connection is enabled on Windows phone

In this short tip I shall be explaining you the simplest way to check the WiFi connection status in Windows Phone. This is a very necessary and required feature for all the apps that use an internet connection.

public bool Checkwificonnection()
{
bool wificonnection =                 Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsWiFiEnabled;
if (wificonnection)
  return true;
else
    return false;
}

c# to singularize – pluralize a word using PluralizationService

in this Post we will talk about singularize – pluralize a word in c#

first you have to add reference  to system.data.entity.design

 

using System.Data.Entity.Design ;

lets go to code …  ^_^

static void Main()
{
Consol.writeLine(string.Format("this is Pluralize for apple {0}" ,Pluralize("apple") )) ; 

Consol.writeLine(string.Format("this is Singularize for cars {0}" ,Singularize ("cars") )) ;
}

 

// this method is useing PluralizationService  Pluralize methos to  Pluralize  the word 

protected string Pluralize(string tablename)
{
var  _Plurale= PluralizationService.CreateService(new System.Globalization.CultureInfo(“en-us”));

return _Plurale.Pluralize(tablename);
}
protected string Singularize (string tablename)
{
var Singular= PluralizationService.CreateService(new System.Globalization.CultureInfo(“en-us”));

return Singular.Singularize(tablename);
}

#MVC Models creator

MVC models Creator  

its tool  that can help developers to develop MVC application without take Care about building  models from Database  the heavy work of putting data annotation attribute like required or maximum length attribute

its easy to use  see the image

1
enter your server credential
2
seelect your databse that you need to generate classes from its tables
3
press on generate button
4
select your folder you want to save files in
5
proccess complete
6
generated class
7
generated resource for the class

8

dnu restore problem

If dnu restore is not a recognized command, you may have missed a prerequisite step

 

so you have to do some steps   then you can use command

  1. Install Visual Studio 2015

Be sure to specify that you want to include the Microsoft Web Developer Tools.

../_images/web-dev-tools.png

  1. Install ASP.NET 5.
This will install the latest ASP.NET 5 runtime and tooling.
  1. Enable the ASP.NET 5 command-line tools. Open a command-prompt and run:

    > dnvm upgrade

 

  1. On Windows 7 and Windows Server 2008 R2 you will also need to install the Visual C++ Redistributable for Visual Studio 2012 Update 4.

jQuery Tips Everyone Should Know

A collection of simple tips to help you  In   jQuery .

Back to Top Button

By using the animate and scrollTop methods in jQuery you don’t need a plugin to create a simple scroll-to-top animation:

 
$('a.top').click(function (e) {
  e.preventDefault();
  $(document.body).animate({scrollTop: 0}, 800);
});
<!-- Create an anchor tag -->
<a class="top" href="#">Back to top</a>

**********

Fix Broken Images Automatically

$('img').on('error', function () {
  $(this).prop('src', 'img/broken.png');
});


Stop the Loading of Links

Sometimes you don’t want links to go to a certain web page nor reload the page; you might want them to do something else like trigger some other script. This will do the trick of preventing the default action:

$('a.no-link').click(function (e) {
  e.preventDefault();
});


Make Two Divs the Same Height

Sometimes you’ll want two divs to have the same height no matter what content they have in them:

$('.div').css('min-height', $('.main-div').height());


Open External Links in New Tab/Window

Open external links in a new browser tab or window and ensure links on the same origin open in the same tab or window:

$('a[href^="http"]').attr('target','_blank');
$('a[href^="//"]').attr('target','_blank');
$('a[href^="'+window.location.origin+'"]').attr('target','_self');

Note:window.location.origin doesn’t work in IE10. This fix takes care of the issue.

Find Element By Text

By using the contains() selector in jQuery you can find text in content of an element. If text doesn’t exists, that element will be hidden:

var search = $('#search').val();
$('div:not(:contains("'+search+'"))').hide();



Trigger On Visibility Change

Trigger javascript when the user unfocuses or refocuses on a tab.

$(document).on('visibilitychange', function(e){
  if (e.target.visibilityState === "visible") {
    console.log('Tab is now in view!');
  } else if (e.target.visibilityState === "hidden") {
    console.log('Tab is now hidden!');
  }
});
for more information see this  :
 https://github.com/AllThingsSmitty/jquery-tips-everyone-should-know


How to Clearing remembered / default login for #SQL Server Management Studio

this  article  to explains how to delete the “remembered” logins for SQL Server Management Studio:

sql

SQL Server Management Studio 2012 delete the file

C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server Management Studio\11.0\SqlStudio.bin

SQL Server Management Studio 2008 delete the file

C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin

SQL Server Management Studio 2005 delete the file – same as above answer but the Vista path. C:\Users\%username%\AppData\Roaming \Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat