Entity Framework – AutoDetectChangesEnabled

From MSDN

When using most POCO entities the determination of how an entity has changed (and therefore which updates need to be sent to the database) is handled by the Detect Changes algorithm. Detect Changes works by detecting the differences between the current property values of the entity and the original property values that are stored in a snapshot when the entity was queried or attached. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.

But some times we need to turn off this feature. for example, I need to upload a excel file it contains a bulk data. At this time AutoDetectChangesEnabled is true then it take a lot time for insert all rows. I can do the data validations at db side.

Just check the difference of AutoDetectChangesEnabled ON and OFF while inserting a bulk data.

Normal way:

namespace TestAutoDetectChangesEnabled
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Time Test - AutoDetectChangesEnabled";
            string[] names = { "Arun", "Raj", "Musthaan", "Majeed", "Muzafir",
                                 "Hari", "Dharma", "Kannan", "Imran", "Santo",
                                 "Rahmath", "Jayesh" };
            Stopwatch sw = new Stopwatch();
            sw.Start();
            var db = new AppContext();
            foreach (var i in Enumerable.Range(1, 20000))
            {
                var student = new Student()
                {
                    Name = names[(new Random().Next(0, 10))],
                    ContactNo = "9870002735",
                    RegNo = i.ToString().PadLeft(7, '0')
                };
                db.Students.Add(student);
                Console.Clear();
                Console.WriteLine("{0} records added", i);
            }
            db.SaveChanges();
            sw.Stop();
            Console.WriteLine("Taked time - {0}", sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }

    public class AppContext : DbContext
    {
        public AppContext()
            : base("AppConnection")
        {

        }
        public DbSet<Student> Students { get; set; }
    }
    public class Student
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string RegNo { get; set; }
        public string ContactNo { get; set; }

    }
}

AutoDetectChangesEnabled-before

After disable AutoDetectChanges

 class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Time Test - AutoDetectChangesEnabled";
            string[] names = { "Arun", "Raj", "Musthaan", "Majeed", "Muzafir",
                                 "Hari", "Dharma", "Kannan", "Imran", "Santo",
                                 "Rahmath", "Jayesh" };
            Stopwatch sw = new Stopwatch();
            sw.Start();
            var db = new AppContext();
            try
            {
                db.Configuration.AutoDetectChangesEnabled = false;

                foreach (var i in Enumerable.Range(1, 20000))
                {
                    var student = new Student()
                    {
                        Name = names[(new Random().Next(0, 10))],
                        ContactNo = "9870002735",
                        RegNo = i.ToString().PadLeft(7, '0')
                    };
                    db.Students.Add(student);
                    Console.Clear();
                    Console.WriteLine("{0} records added", i);
                }
                db.SaveChanges();
            }
            finally
            {
                db.Configuration.AutoDetectChangesEnabled = true;
            }
            sw.Stop();
            Console.WriteLine("Taked time - {0}", sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }

AutoDetectChangesEnabled-after

See the difference, it almost 10x faster. But use it with care. Don’t forget to re-enable detection of changes after the loop — used a try/finally to ensure it is always re-enabled even if code in the loop throws an exception.

CREATE DATABASE PERMISSION DENIED IN DATABASE ‘master’

I have installed SQL SERVER 2008  on my system with Windows 7 operating system installed.
Whenever I try to create a new database it displays an error:
CREATE DATABASE PERMISSION DENIED IN DATABASE 'master'.(Microsoft SQL Server, Error:262).

After a lot of search i am found a solution.

When i start SQL server management studio use ‘sa’ user and not Windows-User. Looks like Windows-user does not have permission.

First, open SQl in administrator mode.
In Security node ,open logins and select users node. In server role tab, tick sysadmin and User Map tab tick master database and select owner in below section.

Click Ok in all windows. Close SQL Management Studio and open it in normal mode.
Now i can create database. No Issues..

 

Musthaan

Seeing the SQL Generated by LINQ to Entity Queries

Sometimes you really, really, really want to see the SQL that LINQ generates when working with the Entity Framework. For instance, in a comment to a recent tip, a reader mentioned that a LINQ to Entities query generated a SQL statement that joined more than 40 tables. The application’s performance was, to say the least, disappointing. If you’re not getting what you expect from your LINQ queries, being able to see the SQL statement can give you real clues in tracking down the problem, as it did with that column’s reader.

There are a couple of free Visual Studio Add-ins that, among their other features, allow you to see the SQL statement for a LINQ query (The LINQ to Entity Query Visualizer, Entity Visualizer). However, developers have had trouble getting those add-ins up and running in some versions of Visual Studio (especially Visual Studio 2010). Fortunately, if all you want to do is see your SQL statement, you can do it in Visual Studio’s debug mode using a little code in the Immediate Window.

The first step, of course, is have a program with a LINQ query as in this example:

Dim en As New northwndEntities

Dim res = From cust In en.Customers

Select cust
If you cast the variable holding the output from the query (res, in this case) to Objects.ObjectQuery then you get access to the ObjectQuery’s ToTraceString property. That property returns the SQL statement that will be issued by your Entity Framework Model. In Visual Basic, you’d type this in the Immediate window:
CType(res, Objects.ObjectQuery).ToTraceString()
In C#, you’d type this:
((System.Data.Objects.ObjectQuery) res).ToTraceString()
For my sample query, the result looked like this in Visual Basic (the C# version includes escape characters for newline and carriage returns):
SELECT [Extent1].[CustomerID] AS [CustomerID],
[Extent1].[CompanyName] AS [CompanyName],
[Extent1].[ContactName] AS [ContactName],
[Extent1].[ContactTitle] AS [ContactTitle],
[Extent1].[Address] AS [Address],
[Extent1].[City] AS [City],
[Extent1].[Region] AS [Region],
[Extent1].[PostalCode] AS [PostalCode],
[Extent1].[Country] AS [Country],
[Extent1].[Phone] AS [Phone],
[Extent1].[Fax] AS [Fax],
[Extent1].[Timestamp] AS [Timestamp]
FROM [dbo].[Customers] AS [Extent1]

Generate Comma Separated List with SELECT statement

Today I have the following situation, where I need to display all related data in comma separated list.

Till today we are using scalar function to display Comma separated list with select statement. That scalar function use the COALESCE() to make comma separated list. Today I found wonderful solution to display comma separated list without scalar function. Let see that.

Scenario:
I have Table like:

CREATE TABLE #test(
field1 VARCHAR(5), field2 VARCHAR(5)
)

Lets insert some data in this table:

INSERT INTO #test
SELECT '001','AAA'
UNION ALL
SELECT '001','BBB'
UNION ALL
SELECT '002','CCC'
UNION ALL
SELECT '003','DDD'
UNION ALL
SELECT '004','EEE'
UNION ALL
SELECT '004','FFF'
UNION ALL
SELECT '004','GGG'

So now my table has Data like:

Get Comma separated List
Get Comma separated List

I want output like:

Get Comma separated List
Get Comma separated List

I come up with very good solution. Let me share with all of you:

SELECT field1,
 SUBSTRING( 
 (
  SELECT ( ', ' + field2)
  FROM #test t2 
  WHERE t1.Field1 = t2.Field1
  ORDER BY t1.Field1, t2.Field1
  FOR XML PATH('')
 ), 3, 1000)
FROM #test t1
GROUP BY field1
Get Comma separated List

Get Comma separated List

My Output will be:

Get Comma separated List

Get Comma separated List

Please make comments, if this helps you in any way

PIVOT Command in SQL Server

There are many cool new features in SQL Server 2005. For example, “Extended Stored Procs“ written in .NET with connections via SqlContext. How cool is this!?!? Check out the new PIVOT command in T-SQL for SQL Server 2005…

declare @sales table
(
[Year] int,
Quarter char(2),
Amount float
)

insert into @sales values(2001, ‘Q1’, 70)
insert into @sales values(2001, ‘Q1’, 150)
insert into @sales values(2002, ‘Q1’, 20)
insert into @sales values(2001, ‘Q2’, 15)
insert into @sales values(2002, ‘Q2’, 25)
insert into @sales values(2001, ‘Q3’, 50)
insert into @sales values(2002, ‘Q3’, 20)
insert into @sales values(2001, ‘Q4’, 90)
insert into @sales values(2001, ‘Q4’, 80)
insert into @sales values(2002, ‘Q4’, 35)

select * from @sales
pivot
(
sum(Amount)
for Quarter
in (Q1, Q2, Q3, Q4)
as p

Year| Q1  |Q2  |Q3 |Q4
———–| ——— |——- |——- |——–
2001| 220 |15  |50 |170
2002| 20  |25  |20 |35

(2 row(s) affected)

Explanation of TRY…CATCH and ERROR Handling

SQL Server 2005 offers a more robust set of tools for handling errors than in previous versions of SQL Server. Deadlocks, which are virtually impossible to handle at the database level in SQL Server 2000, can now be handled with ease. By taking advantage of these new features, you can focus more on IT business strategy development and less on what needs to happen when errors occur. In SQL Server 2005, @@ERROR variable is no longer needed after every statement executed, as was the case in SQL Server 2000. SQL Server 2005 provides the TRY…CATCH construct, which is already present in many modern programming languages. TRY/CATCH helps to write logic separate the action and error handling code. The code meant for the action is enclosed in the TRY block and the code for error handling is enclosed in the CATCH block. In case the code within the TRY block fails, the control automatically jumps to the CATCH block, letting the transaction roll back and resume execution. In addition to this, the CATCH block captures and provides error information that shows you the ID, message text, state, severity and transaction state of an error.

Functions to be used in CATCH block are :

  • ERROR_NUMBER: returns the error number, and is the same value of @@ERROR.
  • ERROR_SEVERITY: returns the severity level of the error that invoked the CATCH block.
  • ERROR_STATE: returns the state number of the error.
  • ERROR_LINE: returns the line number where the error occurred.
  • ERROR_PROCEDURE: returns the name of the stored procedure or trigger for which the error occurred.
  • ERROR_MESSAGE: returns the full message text of the error. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.

You can use these functions anywhere inside a CATCH block, and they will return information regarding the error that has occurred. These functions will return the value null outside of the CATCH block.

Syntax:
BEGIN TRY
{ sql_statement |
statement_block }
END TRY
BEGIN CATCH
{ sql_statement |
statement_block }
END CATCH

The TRY or CATCH block can contain a single T-SQL statement or a series of statements. The CATCH block must follow immediately after the TRY block. The TRY/CATCH block cannot span more than a single batch. In addition, TRY/CATCH block cannot span an IF/ELSE statement.

Example of TRY…CATCH:
BEGIN TRY
DECLARE @X INT
---- Divide by zero to generate Error
SET @X = 1/0
PRINT 'Command after error in TRY block'
END TRY
BEGIN CATCH
PRINT 'Error Detected'
END CATCH
PRINT 'Command after TRY/CATCH blocks'

Above code will return following result:

Error Detected
Command after TRY/CATCH blocks


If all the statements within the TRY block are executed successfully, then processing does not enter the CATCH block, but instead skips over the CATCH block and executes the first statement following the END CATCH statement. Removing SET statement in above code PRINT ‘Error Detected’ statement is not executed, but the PRINT statement within the TRY block is executed, as well as the PRINT statement after the TRY/CATCH block. TRY/CATCH blocks can be nested.

Limitation of TRY…CATCH:

  • Compiled errors are not caught.
  • Deferred name resolution errors created by statement level recompilations. (If process is terminated by Kill commands or broken client connections TRY…CATCH will be not effective)
  • Errors with a severity greater than 10 that do not terminate their database connection are caught in the TRY/CATCH block.

For errors that are not trapped, SQL Server 2005 passes control back to the application immediately, without executing any CATCH block code.

Similar example of TRY…CATCH which includes all the ERROR functions:
USE AdventureWorks;
GO
BEGIN TRY
-- Generate a divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

Reference : Pinal Dave (http://blog.SQLAuthority.com) 

Simple Example of Cursor

This is the simplest example of the SQL Server Cursor. I have used this all the time for any use of Cursor in my T-SQL.
DECLARE @AccountID INT
DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT Account_ID
FROM Accounts
OPEN @getAccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
END
CLOSE @getAccountID
DEALLOCATE @getAccountID