Friday, October 2, 2009

Adding an Entity Data Model to an MVC Application

When we try to access an Entity from a View, we get the following error :

Compiler Error Message: CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

In order to allow the Entities in our Model to be accessible/accessed by the View, we need to add the following reference in the Web.Config file :

<add assembly="System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

SQL Server 2008, SELECT INTO statement

When we create/write a Select statement containing the INTO Clause, SQL Server creates a new table and inserts the results of the Query into the new table. When we run this Select statement containing the INTO Clause more than once, we get an Error : "There is already an object named 'Table1' in the database."

In order to avoid getting this error and to be able to run this Select statement multiple times by selecting into the same table, we need to add the following code to
1. check for the Existence of this table in the database,
2. drop the table if it already exists
3. Then run the Select statement with the Into Clause

IF EXISTS (SELECT * FROM sys.objects WHERE object_id =OBJECT_ID(N'[dbo].[Table1]') AND type in (N'U'))

BEGIN
Drop table Table1
END