<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>entity-framework &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/entity-framework/</link>
	<description>Feed of posts on WordPress.com tagged "entity-framework"</description>
	<pubDate>Mon, 07 Dec 2009 22:28:49 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Retooling]]></title>
<link>http://paymentnetworks.wordpress.com/2009/12/03/retooling/</link>
<pubDate>Fri, 04 Dec 2009 04:12:06 +0000</pubDate>
<dc:creator>Kyle Hodgson</dc:creator>
<guid>http://paymentnetworks.wordpress.com/2009/12/03/retooling/</guid>
<description><![CDATA[The beginning of a software project can be a great time to look at your tools with fresh eyes. Sure,]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>The beginning of a software project can be a great time to look at your tools with fresh eyes.  Sure, you&#8217;ve been doing just fine all along with Visual Studio 2005 for years, but all right, fine now that 2010 is in beta it&#8217;s probably time to take a hard look at Visual Studio 2008.</p>
<p>Let me tell you, I feel as though I have awoken from a deep sleep. I&#8217;ve had my head down managing projects and launching programs for so long that I feel like a decade or more has passed. You have to keep in mind, I wrote a lot of code that looked like this:</p>
<pre style="padding-left:30px;">SqlCommand scGetResults = new SqlCommand();
scGetReults.Connection = dbConn;
scGetResults.CommandType = System.Data.CommandType.StoredProcedure;
scGetResults.Parameters.AddWithValue("@programid", argProgrmId);
DataReader drResutls = scGetResults.ExecuteReader();
if (drResults.HasRows() ) {
     while ( drResults.Read() ) {
          // do something
     }
}</pre>
<p>And really, this doesn&#8217;t look a lot different from the PHP I was writing five years ago, with the exception of parameters:</p>
<pre style="padding-left:30px;"><code>mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
 printf("ID: %s  Name: %s", $row[0], $row[1]);
}
 </code></pre>
<p>So to go to StackOverFlow DevDays in October and see a live coding demo using LINQ I was blown away!  I mean how much cooler is that?</p>
<pre style="padding-left:30px;">var myList = (
     from c in _db.CustomerSet
     where c.Account.Balance &#62; minAccountBal &#38;&#38; c.Program.OwnerId == i
     select c).ToList();</pre>
<p>Upon further inspection, LINQ can&#8217;t be used everywhere &#8211; our app requires access to hundreds of databases (scaling to thousands)  using stored procedures; and, well, Entity Framework does not support stored procedures very nicely yet.  LINQ-to-SQL does, but Microsoft has made <a href="http://stackoverflow.com/questions/973506/asp-net-mvc-linq-to-sql-or-entities" target="_blank">noises</a> that seem to indicate it won&#8217;t be supported in future.</p>
<p>I have heard they&#8217;re fixing that in .NET 4.0, which ships with VS2010&#8230; something tells me I won&#8217;t be holding my breath for its release.  I am <em>loving</em> ASP.NET/MVC however!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Issues when trying to access a LINQ to Entity Layer from a WCF Service]]></title>
<link>http://duthiega.wordpress.com/2009/12/01/issues-when-trying-to-access-a-linq-to-entity-layer-from-a-wcf-service/</link>
<pubDate>Tue, 01 Dec 2009 11:46:11 +0000</pubDate>
<dc:creator>Gordon Duthie</dc:creator>
<guid>http://duthiega.wordpress.com/2009/12/01/issues-when-trying-to-access-a-linq-to-entity-layer-from-a-wcf-service/</guid>
<description><![CDATA[Listed below are some issues and solution you may come across when trying access a LINQ to Entity la]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Listed below are some issues and solution you may come across when trying access a LINQ to Entity layer from a WCF Service located in a separate project.</p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong><strong>Problem: </strong><br />
</strong>Argument Exception: &#8220;The specified named connection is either not found in the configuration, not intended to be used with the EntityClient Provider, not valid.&#8221;</p>
<p><a href="http://duthiega.wordpress.com/files/2009/12/argument-exception.png"><img class="alignnone size-full wp-image-25" title="Argument Exception" src="http://duthiega.wordpress.com/files/2009/12/argument-exception.png" alt="Argument Exception: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid" width="452" height="265" /></a></p>
<p><strong>Solution: </strong></p>
<p><strong><span style="font-weight:normal;">The class library which contains the EDMX file contains an app.config file with the entity connection string. When access this from the WCF layer, there is no reference to it unless you include it in the web.config of the WCF layer</span></strong></p>
<p>To fix the problem, copy the connection string from the app.config to the ConnectionStrings section of the web.config of the WCF project.</p>
<p>However, on doing this, you may receive another exception message:</p>
<p>MetadataException: Unable to load the specified metadata resource.<br />
<a href="http://duthiega.wordpress.com/files/2009/12/metadataexception.png"><img src="http://duthiega.wordpress.com/files/2009/12/metadataexception.png" alt="MetadataException : Unable to load the specified metadata resource" title="Metadataexception" width="452" height="252" class="alignnone size-full wp-image-29" /></a></p>
<div class="context"> connectionString=&#8221;metadata=res://*/Model.Project.csdl&#124;res://*/Model.Project.ssdl&#124;res://*/Model.Project.msl;
</div>
<p>to</p>
<div class="context"> connectionString=&#8221;metadata=res://*/;</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Entity Framework fácil]]></title>
<link>http://davidlinan.wordpress.com/2009/11/29/entity-framework-facil/</link>
<pubDate>Sun, 29 Nov 2009 18:56:04 +0000</pubDate>
<dc:creator>David Liñán</dc:creator>
<guid>http://davidlinan.wordpress.com/2009/11/29/entity-framework-facil/</guid>
<description><![CDATA[Todos los que nos dedicamos al desarrollo de software sabemos que siempre hay una tarea inevitable. ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Todos los que nos dedicamos al desarrollo de software sabemos que siempre hay una tarea inevitable. Me estoy refiriendo a la grabación y recuperación de datos en una base de datos relacional. Pero si además nuestra aplicación es de cierta complejidad, con un modelo de dominio y entidades de negocio, la cosa se complica.  No basta con recuperar los datos, además hay que &#8220;convertirlos&#8221; de alguna forma en nuestras entidades de negocio. Para grabarlos hay que hacer lo contrario: &#8220;convertir&#8221; nuestras entidades en datos grabables con una consulta SQL. Para llevar a cabo estas tareas en .NET hay varias opciones:</p>
<ul>
<li>Mediante un <em>DataReader</em> transferir manualmente los valores de las filas a las propiedades de las entidades.</li>
<li>Usar un <em>DataCommand</em> para insertar o actualizar datos, pasándole los valores de las propiedades de una entidad.</li>
<li>Usar <em>DataSets</em> tipados como entidades.</li>
<li>Leer un <em>DataTable</em> para transferir los valores de sus columnas a las entidades y viceversa.</li>
<li>Usar una herramienta ORM (Object-Relational Mapping) como <em>NHibernate</em>, para asociar nuestras entidades a tablas y sus propiedades a valores de columnas.</li>
</ul>
<p>Vamos a centrarnos en este post en la última opción y cómo se puede llevar a cabo usando <em>Entity Framework</em> (EF).</p>
<p>EF es, como su nombre indica, un framework que nos permite mapear manualmente asociaciones entre entidades de negocio y una base de datos. De hecho, nos permite generar un modelo de dominio con estas entidades a partir de una base se datos. En la práctica lo más frecuente es hacer lo opuesto: a partir de un modelo de dominio generar un modelo de datos, pero la versión de EF incluida con la versión 3.5 del Framework  no lo permite. En cualquier caso, siempre es posible modificar posteriormente el modelo de dominio, agregar relaciones de herencia, partir entidades, etc&#8230; y mantenerlo sincronizado con la base de datos.</p>
<h4>Primeros pasos con EF</h4>
<p>Lo primero que hay que hacer, si no lo hemos hecho ya, es instalar el SP1 de Visual Studio 2008. De lo contrario no podremos usar algunas plantillas y librerías que necesitaremos. Seguidamente tendremos que tener la base de datos (o parte de ella) ya creada.</p>
<p>Vamos a partir de un ejemplo sencillo y bastante común: una base de datos que contiene pedidos. Por simplificar vamos a tener solamente tres tablas con un número reducido de campos, donde las claves primarias son autonuméricos:</p>
<div id="attachment_23" class="wp-caption aligncenter" style="width: 460px"><a href="http://davidlinan.wordpress.com/files/2009/11/database-model.png"><img class="size-full wp-image-23" title="Database model" src="http://davidlinan.wordpress.com/files/2009/11/database-model.png" alt="" width="450" height="134" /></a><p class="wp-caption-text">Base de datos original</p></div>
<h4>Crear un modelo de dominio</h4>
<p>Personalmente prefiero crear el modelo de dominio en un proyecto de librería de clases separado, de modo que eso haremos. Posteriormente agregamos a nuestro proyecto un nuevo elemento <em>ADO.NET Entity DataModel</em>:</p>
<div id="attachment_18" class="wp-caption aligncenter" style="width: 460px"><a href="http://davidlinan.wordpress.com/files/2009/11/2-entity-data-model1.png"><img class="size-full wp-image-18" title="Agregando un nuevo" src="http://davidlinan.wordpress.com/files/2009/11/2-entity-data-model1.png" alt="" width="450" height="236" /></a><p class="wp-caption-text">Agregando un nuevo Entity Data Model</p></div>
<p style="text-align:center;">
<p>Los siguientes pasos son indicar que queremos generar el modelo a partir de una base de datos  y posteriormente indicar la conexión a esa base de datos. Hay que tener en cuenta que como  resultado se creará un fichero de configuración con la cadena de conexión correspondiente.</p>
<div id="attachment_19" class="wp-caption aligncenter" style="width: 460px"><a href="http://davidlinan.wordpress.com/files/2009/11/3-generate-from-database.png"><img class="size-full wp-image-19" title="3 Generate from Database" src="http://davidlinan.wordpress.com/files/2009/11/3-generate-from-database.png" alt="" width="450" height="400" /></a><p class="wp-caption-text">Generando un modelo desde una base de datos</p></div>
<div id="attachment_20" class="wp-caption aligncenter" style="width: 460px"><a href="http://davidlinan.wordpress.com/files/2009/11/4-select-connection.png"><img class="size-full wp-image-20" title="4 Select connection" src="http://davidlinan.wordpress.com/files/2009/11/4-select-connection.png" alt="" width="450" height="400" /></a><p class="wp-caption-text">Seleccionando la conexión</p></div>
<p>El último paso consiste en seleccionar las tablas a partir de las cuales se generarán las entidades. También hay que definir el espacio de nombre donde se definirán estas entidades generadas (en nuestro caso <em>Acme.Model</em>). Es posible hacer el mapeo a vistas y procedimientos almacenados, pero eso es un tema para otro post.</p>
<div id="attachment_21" class="wp-caption aligncenter" style="width: 460px"><a href="http://davidlinan.wordpress.com/files/2009/11/5-seleccionar-tablas.png"><img class="size-full wp-image-21" title="5 Seleccionar tablas" src="http://davidlinan.wordpress.com/files/2009/11/5-seleccionar-tablas.png" alt="" width="450" height="400" /></a><p class="wp-caption-text">Seleccionando las tablas</p></div>
<p>Una vez hecho esto se habrá añadido a nuestro proyecto un fichero con extensión .<em>edmx</em>. No vamos a entrar en detalles sobre su contenido, por ahora basta  con saber que en él se implementan una serie de clases parciales, una por cada tabla. Estas clases son las entidades de negocio y se pueden ampliar para incluir nuestros métodos de negocio, simplemente añadiendo al proyecto otra clase parcial con el mismo nombre. También se definen los mapeos entre los campos de la base de datos y las propiedades de las entidades.</p>
<p>Por defecto el modelo creado tiene entidades con los mismos nombres que las tablas. Las propiedades tienen también los mismos nombres que las columnas de las tablas. Es aconsenjable cambiar estos nombres si se considera que pueden inducir a confusión. En nuestro caso hemos renombrado las entidades en singular.</p>
<div id="attachment_22" class="wp-caption aligncenter" style="width: 460px"><a href="http://davidlinan.wordpress.com/files/2009/11/6-modelo.png"><img class="size-full wp-image-22" title="6 Modelo" src="http://davidlinan.wordpress.com/files/2009/11/6-modelo.png" alt="" width="450" height="181" /></a><p class="wp-caption-text">Modelo generado</p></div>
<p>También se puede ver que hay relaciones entre las entidades. Corresponden a restricciones FK de la base de datos, aunque en el modelo EF se transforman en <em>propiedades de navegación</em>. Por ejemplo, la entidad <em>Order</em> tiene una propiedad <em>Details</em> para obtener todos sus detalles asociados. La entidad <em>Detail</em> tiene una propiedad <em>Order</em> que permite acceder a datos del pedido.</p>
<p>Y la pregunta obvia es: ¿qué se puede hacer con este modelo que hemos generado?. Por lo pronto diremos que todo el código de lectura y escritura en la base de datos subyacente y su paso al modelo de objetos ya no tendremos que escribirlo. No hace falta decir la cantidad de tiempo y esfuerzo que ahorra esto. Tampoco tendremos que preocuparnos de abrir y cerrar conexiones o de transacciones, EF se encarga de ello por nosotros. El siguiente punto es ver cómo se usa este modelo en una aplicación.</p>
<h4>Usar el modelo de dominio</h4>
<p>Todo gira en torno a un objeto que se generó en el paso anterior y que contiene todas las otras entidades. Este objeto contenedor hereda de <em>System.Data.Objects.ObjectContext</em> y su nombre lo hemos definido al principio, cuando elegimos la conexión a la base de datos (en nuestro caso es <em>OrderContext</em>). No obstante, este nombre y también el de su espacio de nombres se puede cambiar editando el fichero fuente del diseñador del modelo de datos (en nuestro caso, <em>Orders.Designer.cs</em>).</p>
<p>Para probar el modelo recién generado hemos añadido a la solución una aplicación de consola, a la cual le añadimos una referencia al proyecto anterior y además una referencia al ensamblado <em>System.Data.Entity</em>, de lo contrario no se podría compilar. También es necesario agregar un fichero de configuración a esta nueva aplicación e incluir en él la cadena de conexión a la base de datos.</p>
<h4>Insertar nuevos datos</h4>
<p>La inserción en tablas raíz se hace a través de los métodos de <em>OrderContext</em> (los cuales, recordemos, son generados automáticamente). Tenemos tres entidades en nuestro modelo y tenemos tres métodos <em>AddToOrders()</em>, <em>AddToDetails()</em> y <em>AddToProducts()</em>. Por ejemplo, veamos cómo se insertarían dos nuevos productos:</p>
<pre class="brush: csharp;">
 static void Main(string[] args)
 {
 // Referencia al contenedor
 OrderContext context = new OrderContext();
 // Paso 1: Insertar productos
 // Inserta un producto
 Product product = new Product()
 {
 Name = &#34;Laser Sabre&#34;,
 Description = &#34;Original Star Wars Laser Sabre, available in three colors&#34;,
 Price = 350.90
 };
 context.AddToProducts(product);
 // Inserta otro producto
 Product anotherProduct = new Product()
 {
 Name = &#34;Darth Vader's Mask&#34;,
 Description = &#34;A excellent replica of the Dark Lord's Mask and helmet&#34;,
 Price = 650.90
 };
 context.AddToProducts(anotherProduct);
 context.SaveChanges();
</pre>
<p>Cuando se invoca al método <em>SaveChanges()</em> se llevan a cabo TODOS los cambios dentro de una transacción. En este caso se insertarían ambos productos. Posteriormente estos datos se podrían recuperar a través de la colección <em>Products</em>, también generada de forma automática.</p>
<pre class="brush: csharp;">

// Paso 2: obtener la lista de productos
 foreach (Product p in context.Products)
 {
 Console.WriteLine(p.Name + &#34; - &#34; + p.Description);
 }
</pre>
<h4>Grabar datos en tablas relacionadas</h4>
<p>En nuestro ejemplo tenemos una entidad <em>Order</em> con datos de pedidos, la cual a su vez tiene una propiedad <em>Details</em> que contiene una colección de detalles de pedido. Veamos cómo se grabaría un pedido con dos detalles, uno correspondiente a cada producto:</p>
<pre class="brush: csharp;">

// Paso 3: crear un pedido con ambos productos
 Order order = new Order();
 foreach (Product p in context.Products)
 {
 Detail det = new Detail();
 det.Product = p;
 det.Price = p.Price;
 det.Quantity = 1;
 order.Amount = order.Amount + det.Quantity * det.Price;
 order.Details.Add(det);
 }
 order.VAT = 16;
 order.Total = order.Amount + order.Amount * (order.VAT / 100);
 context.AddToOrders(order);
 context.SaveChanges();
</pre>
<p>Al principio creamos un nuevo pedido y en el bucle <em>foreach</em> recorremos los productos y por cada uno creamos un detalle, los cuales insertamos en <em>Order.Details</em>. Al final grabamos todos los cambios con una llamada a <em>SaveChanges()</em>. Vale la pena mencionar que, a nivel de base de datos, los valores de la clave en <em>DETAILS</em> han sido establecidos automáticamente por EF a partir de los de las claves externas.</p>
<h4>Recuperar datos de tablas relacionadas</h4>
<p>Es muy fácil recuperar todos los datos relacionados de un pedido, aunque algunos puntos no son tan obvios. Veamos el código:</p>
<pre class="brush: csharp;">

// Paso 4: recuperar el pedido y datos asociados de la base de datos y actualizarlo
 order = (from ord in context.Orders
 where ord.Id == 1
 select ord).First();
 if (!order.Details.IsLoaded)
 order.Details.Load();
 foreach (Detail det in order.Details)
 {
 det.Quantity = det.Quantity + 1;
 order.Amount = order.Amount + det.Price;
 }
 order.Total = order.Amount + order.Amount * (order.VAT / 100);
 context.SaveChanges();
</pre>
<p>La primera consulta LINQ obtiene el pedido cuyo número es 1. El problema es que no devuelve un pedido, sino una colección con un único pedido. Por ello aplicamos el operador <em>First()</em>.</p>
<p>Por otra parte, los detalles del pedido no se cargan automáticamente. La propiedad <em>order.Details.IsLoaded</em> nos indica si se ha cargado o no ( y por tanto, en un primer momento tiene valor <em>false</em>). Para cargar los detalles del pedido invocamos al método <em>order.Details.Load()</em>.</p>
<p>Finalmente, tras actualizar todos los datos grabamos todo de golpe mediante una llamada a <em>SaveChanges()</em>.</p>
<p>Borrar datos de tablas relacionadas</p>
<p>Finalmente veamos cómo borrar datos de tablas relacionadas, en este caso un pedido completo con sus detalles. Este método que veremos implica cargar primero el pedido con sus detalles para posteriormente borrarlo, lo cual no parece muy eficiente. Hay otra forma de borrar datos sin tener que cargarlos pero es un tema para otro post.</p>
<pre class="brush: csharp;">

// Paso 5: borrar el pedido y los detalles
 order = (from ord in context.Orders
 where ord.Id == 1
 select ord).First();
 if (!order.Details.IsLoaded)
 order.Details.Load();
 order.Details.Clear();
 context.DeleteObject(order);
 context.SaveChanges();
</pre>
<p>En primer lugar seleccionamos el pedido y cargamos sus detalles. Mediante el método <em>Clear()</em> de <em>order.Details</em> los eliminamos del pedido (y posteriormente se eliminarán de la base de datos). Luego borramos el pedido mediante <em>context.DeleteObject()</em>. Lo que realmente ocurre es que tanto el pedido como los detalles se marcan para borrar, lo cual se lleva a cabo finalmente en la llamada a <em>context.SaveChanges()</em>.</p>
<h4>Conclusiones rápidas</h4>
<p>Mediante <em>Entity Framework</em> hemos creado en segundos un pequeño modelo de dominio plenamente operativo, cuyo desarrollo manual nos habría llevado bastante más tiempo. Por supuesto, se trataba de un caso sencillo y no hemos visto características avanzadas como herencia o partición de entidades. Tampoco hemos visto cómo enlazar entidades a procedimientos almacenados, algo que en aplicaciones de gestión reales tendríamos que hacer casi con toda seguridad. Pero estas son otras historias y deben ser contadas en otra ocasión.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[راه های دسترسی به داده در دات نت فریم ورک!]]></title>
<link>http://farasun.wordpress.com/2009/11/29/data-access-ways-in-net-framework/</link>
<pubDate>Sun, 29 Nov 2009 15:09:50 +0000</pubDate>
<dc:creator>ایمان</dc:creator>
<guid>http://farasun.wordpress.com/2009/11/29/data-access-ways-in-net-framework/</guid>
<description><![CDATA[در اکثر برنامه های کامپیوتری نیاز به ذخیره و بازیابی داده ها وجود دارد. داده هایی که بدون آن ها سیست]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><blockquote>
<p style="text-align:justify;">در اکثر برنامه های کامپیوتری نیاز به ذخیره و بازیابی داده ها وجود دارد. داده هایی که بدون آن ها سیستم نرم افزاری ما معنایی ندارد. برنامه نویسان معمولاً راه های مختلفی برای این کار سراغ دارند. کسانی که با دات نت فریم ورک برنامه نویسی می کنند راه های مختلفی برای دسترسی به داده ها دارند. در این مطلب با تکنولوژی های مایکروسافت برای این کار آشنا خواهیم شد و سه ORM معروف دنیای دات نت را معرفی خواهیم کرد. مایکروسافت انتخاب های زیادی برای دسترسی به داده ها به برنامه نویسان دات نت می دهد که شما باید با بررسی آن ها و با توجه به نیازهای خودتان یکی از آن ها را انتخاب کنید.</p>
</blockquote>
<h2>ADO.NET</h2>
<p style="text-align:justify;"><strong>ADO.NET</strong> مجموعه ای از کامپوننت هاست که برنامه نویسان می توانند از آن ها برای برقراری ارتباط با دیتابیس های مختلف استفاده کنند. ADO.NET بخشی از کتابخانه کلاس های پایه دات نت فریم ورک است که توسط مایکروسافت توسعه داده می شود. برنامه نویسان به صورت گسترده از این تکنولوژی برای دسترسی و دستکاری داده های ذخیره شده در یک دیتابیس رابطه ای استفاده می کنند. ADO.NET می تواند با اکثر دیتابیس های موجود کار کند، هر چند به صورت پیش فرض در دات نت فریم ورک فقط فراهم کننده های SQL Server، OleDb و Odbc وجود دارد، افراد و شرکت های دیگر فراهم کننده های دیتابیس های دیگر را برای دات نت ایجاد کرده اند.</p>
<p style="text-align:justify;">برای هر <strong>Provider</strong> کامپوننت هایی وجود دارند که برنامه نویس با استفاده از آن ها به مقصودش می رسد. به طور مثال برای استفاده از SQL Server در روش ADO.NET کامپوننت هایی مانند <strong>SQLConnection</strong> و <strong>SQLCommand</strong> وجود دارد که با استفاده از آن ها می توانید یک دستور SQL را روی داده های موجود در یک دیتابیس SQL Server اجرا کنید. با SQLConnection به دیتابیس موجود در SQL Server وصل می شویم و با استفاده از یک SQLCommand می توانیم یک عبارت T-SQL را که می تواند دستور INSERT, UPDATE, DELETE یا SELECT باشد یا حتی یک Stored Procedure یا عبارت DDL باشد را برای مقصود خاصی روی دیتابیس اجرا کنیم. چون ADO.NET در مورد سینتاکس دیتابیس چیزی نمی داند، دستورات را به صورت یک رشته ساده به SQLCommand می دهیم و این شیء نیز به صورت مستقیم به دیتابیس دستور می دهد.</p>
<p style="text-align:left;"><code><span style="color:#0000ff;">string</span> query = <span style="color:#ff0000;">"SELECT * FROM tblCustomers"</span>;<br />
<span style="color:#33cccc;">SqlConnection</span> con = <span style="color:#0000ff;">new</span> <span style="color:#00ccff;">SqlConnection</span>(cnnString);<br />
<span style="color:#00ccff;">SqlCommand</span> command = <span style="color:#0000ff;">new</span> <span style="color:#00ccff;">SqlCommand</span>(query, con);<br />
con.Open();<br />
<span style="color:#00ccff;">SqlDataReader</span> reader = command.ExecuteReader();<br />
<span style="color:#0000ff;">while</span> (reader.Read())<br />
{<br />
Response.Write(reader.GetInt32(0) +<br />
reader.GetString(1));<br />
}</code></p>
<p style="text-align:justify;">نکته ای که باید در مورد ADO.NET بدانید این است که برای استفاده از هر سیستم دیتابیس رابطه ای، مجموعه کامپوننت های جدایی وجود دارد. در مثال بالا از آبجکت های مربوط به SQL Server استفاده کردیم. اگر بخواهید مثلاً از یک دیتابیس اوراکل در برنامه خود استفاده کنید، بایستی از کامپوننت های مربوط به اوراکل استفاده کنید. خوشبختانه تمام این کامپوننت ها بر پایه یک Interface ساخته شده اند، این یعنی شما می توانید با استفاده از کلاس DbProviderFactory برنامه ای بسیازید که با چند نوع دیتابیس مختلف کار کند.</p>
<h2>Linq to SQL</h2>
<p style="text-align:justify;">مایکروسافت با دات نت فریم ورک 3.0 و 3.5 یک <a title="Object Relational Mapping on Wikipedia" href="http://en.wikipedia.org/wiki/Object-Relational_mapping" target="_blank"><strong>ORM</strong></a> به نام <strong>Linq to SQL</strong> را به عنوان بخشی از پروژه LINQ خود عرضه کرد. این شرکت مدت ها پیش از آن قول داده بود که یک ORM برای دات نت فریم ورک طراحی کند اما تا نسخه 3.0 دات نت فریم ورک خبری از آن پروژه نشد. Linq to SQL به شما اجازه می دهد که کوئری های LINQ را روی دیتابیس های SQL Server اجرا کنید. علاوه بر این از یک Mapping Framework بهره می برد که به برنامه نویسان اجازه Map کردن جدول های یک دیتابیس را به کلاس ها و بالعکس می دهد. این کار در ویژوال استادیو می تواند به صورت ویژوال یا کدنویسی انجام گیرد. به این صورت که برای هر جدول از دیتابیس یک کلاس تعریف می شود که هر ستون از یک جدول به عنوان یک Property درون آن کلاس تعریف می شود.</p>
<p style="text-align:justify;">
<div id="attachment_1221" class="wp-caption aligncenter" style="width: 460px"><a title="برای دیدن نمای بزرگتر کلیک کنید" href="http://farasun.wordpress.com/files/2009/11/linq-to-sql-large.png" target="_blank"><img class="size-full wp-image-1221" title="linq-to-sql-thumb" src="http://farasun.wordpress.com/files/2009/11/linq-to-sql-thumb.png" alt="" width="450" height="253" /></a><p class="wp-caption-text">نمایی از ابزار طراحی ویژوال Linq to SQL</p></div>
<p style="text-align:justify;">به مثال زیر توجه کنید :<br />
<code><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> Customer<br />
{<br />
[<span style="color:#00ccff;">Column</span>(Name=<span style="color:#ff0000;">"CustomerID"</span>,IsPrimaryKey = <span style="color:#0000ff;">true</span>)]<br />
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">long</span> ID<br />
{<br />
<span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> _ID;}<br />
<span style="color:#0000ff;">set</span> { _ID = value;}<br />
}<br />
[<span style="color:#00ccff;">Column</span>(Name = <span style="color:#ff0000;">"CustomerName"</span>)]<br />
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> Name<br />
{<br />
<span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> _name; }<br />
<span style="color:#0000ff;">set</span> { _name = value; }<br />
}<br />
}</code><br />
کلاس بالا به جدول tblCustomers که دارای دو ستون CustomerID و CustomerName است Map می شود. قبل از اینکه بخواهید از Linq to SQL استفاده کنید باید این کلاس ها را تعریف کنید. ویژوال استادیو 2008 دارای ابزاری است که به صورت ویژوال به شما امکان Map کردن جدول های یک دیتابیس SQL Server را به کلاس های دات نت می دهد. این ابزار می تواند به صورت اتوماتیک کلاس های مورد نیاز شما را از روی مدل دیتابیس بسازد، و حتی اجازه تغییرات دستی و ایجاد Viewهای مختلف از دیتابیس را به شما می دهد. عملیات Mapping با استفاده از DataContext (که یک رشته اتصال به سرور نیاز دارد) پیاده سازی می شود. سپس شما قادر خواهید بود کوئری های LINQ خود را روی دیتابیس موجود در سرور اجرا کنید، که البته این کوئری ها ابتدا به دستوارت T-SQL متناظر ترجمه و سپس روی دیتابیس مورد نظر اجرا می شوند.</p>
<h2>Entity Framework</h2>
<p style="text-align:justify;"><a href="http://www.microsoft.com/sqlserver/2008/en/us/ado-net-entity.aspx" target="_blank"><strong>Entity Framework</strong></a> یک فریم ورک ORM برای دات نت فریم ورک است که نسخه یک آن به همراه دات نت فریم ورک 3.5 سرویس پک 1 عرضه شد اما مورد استقبال توسعه دهندگان قرار نگرفت. نسخه 2 این فریم ورک به صورت بتا به عنوان بخشی از ویژوال استادیو 2010 قابل دسترس است.<strong> ADO.NET Entity Framework</strong> نام اصلی این فریم ورک است و جزئی از تکنولوژی ADO.NET است.</p>
<p style="text-align:justify;">
<div id="attachment_1225" class="wp-caption aligncenter" style="width: 460px"><img class="size-full wp-image-1225" title="SFS_EF_model" src="http://farasun.wordpress.com/files/2009/11/sfs_ef_model.jpg" alt="ابزار طراحی Entity Framework در ویژوال استادیو" width="450" height="295" /><p class="wp-caption-text">ابزار طراحی Entity Framework در ویژوال استادیو</p></div>
<p style="text-align:justify;">Entity Framework مدل رابطه ای موجود در یک دیتابیس را به مدل مفهمومی تبدیل می کند و آن را به اپلیکیشن ما تحویل می دهد. در مدل رابطه ای عناصر ترکیبی از جداول هستند، به همراه کلید های اصلی و خارجی که جدول ها را به هم مرتبط می سازند. برعکس آن، انواع موجودیت ها مدل مفهومی داده را تعریف می کنند. انواع موجودیت  اجتماعی از چند فیلد است (هر فیلد به یک ستون از دیتابیس Map می شود) و می تواند شامل اطلاعات از چند جدول فیزیکی باشد. انواع موجودیت می توانند به هم مرتبط باشند، مستقل از ارتباطاتی که در مدل فیزیکی دارند. شمای منطقی و نگاشت (mapping) آن به شمای فیزیکی به عنوان یک Entity Data Model یا EDM نمایش داده می شوند که مشخصات EDM در یک فایل XML ذخیره می شود. Entity Framework از EDM برای انجام عملیات نگاشت و دادن قابلیت کار با موجودیت ها به اپلیکیشن استفاده می کند. Entity Framework اطلاعات مورد نیاز هر موجودیت را با Join کردن چندین جدول از مدل فیزیکی (دیتابیس) بدست می آورد. هنگامی که اطلاعات یک موجودیت آپدیت می شود، Entity Framework بررسی می کند که داده ها مربوط به کدام یک از جدول های موجود در دیتابیس هستند، سپس آن ها را با دستور SQL مناسب آپدیت می کند.</p>
<p style="text-align:justify;">هر چند Entity Framework و Linq to SQL بسیار شبیه به هم به نظر می رسند، هر دو ابزارهایی برای طراحی گرافیکی و ویزاردی برای نگاشت یک دیتابیس به مدل شیء گرا دارند و هر دو می توانند از کوئری های LINQ برای مقصود خاصی استفاده کنند، اما با هم تفاوت هایی هم دارند. بیان تفاوت های این دو در این مطلب جایی ندارد.</p>
<h2>NHibernate</h2>
<p style="text-align:justify;"><img class="alignright" title="orm" src="../files/2009/11/orm.png" alt="" width="280" height="190" />نمی توان در مورد ORMها در دات نت صحبت کرد اما نام <a href="http://www.nhforge.org/" target="_blank"><strong>NHiernate</strong></a> را ذکر نکرد. NH یک فریم ورک ORM اوپن سورس برای دات نت فریم ورک است که از روی پروژه موفق Hibernate جاوا وارد دنیای دات نت شد. توضیحات بیشتر در مورد NHibernate توضیحات اضافی است، زیرا این فریم ورک هم وظیفه ORMهای دیگر را انجام می دهد. اکثر برنامه نویسانی که از NH برای نگاشت استفاده می کنند، ابتدا کلاس های خود را تعریف می کنند و سپس با استفاده از یک فایل XML آن ها را به جدول های دیتابیس Map می کنند. Linq to SQL و Entity Framework برخلاف NHibernate از روش Model-first یا مبتنی در دیتابیس استفاده می کنند، به این معنی که هر دو ORM تصور می کنند شما دیتابیسی در اختیار دارید که می خواهید آن به تعدادی آبجکت Map کنید.</p>
<p>در مورد Nhibernate بیش از این صحبت نمی کنم، آقای وحید نصیری در<a href="http://vahidnasiri.blogspot.com/search/label/NHibernate" target="_blank"><strong> اینجا</strong></a> به صورت کامل در مورد این ORM محبوب نوشته است.</p>
<p><span style="color:#ffffff;">farasun.wordpress.com</span></p>
<p>انتخاب از میان روش های بالا به عهده خود شماست. در این مطلب کوتاه نمی توان به بررسی تمام زوایا و تفاوت های میان آن ها پرداخت. در مطالب آینده سعی میکنم در مورد نحوه استفاده از هر کدام یک مثال عملی بزنم (البته به جز NHibernate).</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Using Ext JS Grid with ASP.NET MVC]]></title>
<link>http://nraykov.wordpress.com/2009/11/29/using-ext-js-grid-with-asp-net-mvc/</link>
<pubDate>Sun, 29 Nov 2009 13:51:14 +0000</pubDate>
<dc:creator>Nikolay Raykov</dc:creator>
<guid>http://nraykov.wordpress.com/2009/11/29/using-ext-js-grid-with-asp-net-mvc/</guid>
<description><![CDATA[ASP.NET MVC is the new cool kid on the block of Microsoft platforms. I have been using it for a litt]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>ASP.NET MVC is the new cool kid on the block of Microsoft platforms. I have been using it for a little over half an year and I can say that I like it much more than ASP.NET. Why is that?</p>
<ol>
<li>No more viewstate which adds an additional overhead on your page</li>
<li>Clean separation of concerns through the MVC pattern</li>
<li>Going back to the basics (standard HTML controls) &#8211; most of the ASP.NET server controls do not work with ASP.NET MVC because there is no viewstate and the notion of postbacks</li>
</ol>
<p>This would be the first of a series of blog posts that I would write about ASP.NET MVC and some performance techniques that could get the most out of it. We will start by building a simple application that uses Ext JS Grid to display employees data that is fetched from the AdventureWorks database. Since jQuery is being shipped with Visual Studio for over a year now I will be using it as well &#8211; as an adapter to Ext JS (I am a big fan of jQuery).</p>
<p>I am going to create my app using Visual Stidio 2010 Beta 2 which ships with ASP.NET MVC 2 Beta. If you are using Visual Studio 2008 you have to download the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=4817cdb2-88ea-4af4-a455-f06b4c90fd2c&#38;displaylang=en" target="_blank">Beta</a> and install it on your machine. First we start by creating a new ASP.NET MVC Project.</p>
<p style="text-align:center;">
<div id="attachment_65" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.wordpress.com/files/2009/11/step_11.png"><img class="size-full wp-image-65" title="New ASP.NET MVC Project" src="http://nraykov.wordpress.com/files/2009/11/step_11.png" alt="New ASP.NET MVC Project" width="600" height="413" /></a><p class="wp-caption-text">New ASP.NET MVC Project</p></div>
<p>Next I am copying the necessary files that are needed for Ext JS &#8211; ext-all.debug.js and ext-jquery-adapter.js to an extjs folder I created under my Scripts folder which was created for me by the ASP.NET MVC project template. I will use the latest version of the library &#8211; <a href="http://www.extjs.com/" target="_blank">Ext JS 3.0.3</a>.</p>
<p>In the next step we need to include the css and js files &#8211; I will put them in the master page (located under Views/Shared folder):</p>
<pre style="overflow:auto;"><span style="color:#0000ff;">&#60;</span><span style="color:#800000;">link</span> <span style="color:#ff0000;">href</span><span style="color:#0000ff;">="../../Content/resources/css/ext-all.css"</span> <span style="color:#ff0000;">rel</span><span style="color:#0000ff;">="stylesheet"</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">="text/css"</span> <span style="color:#0000ff;">/&#62;</span>
<span style="color:#0000ff;">&#60;</span><span style="color:#800000;">script</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">="text/javascript"</span> <span style="color:#ff0000;">src</span><span style="color:#0000ff;">="../../Scripts/jquery-1.3.2.js"</span><span style="color:#0000ff;">&#62;&#60;/</span><span style="color:#800000;">script</span><span style="color:#0000ff;">&#62;</span>
<span style="color:#0000ff;">&#60;</span><span style="color:#800000;">script</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">="text/javascript"</span> <span style="color:#ff0000;">src</span><span style="color:#0000ff;">="../../Scripts/extjs/ext-jquery-adapter.js"</span><span style="color:#0000ff;">&#62;&#60;/</span><span style="color:#800000;">script</span><span style="color:#0000ff;">&#62;</span>
<span style="color:#0000ff;">&#60;</span><span style="color:#800000;">script</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">="text/javascript"</span> <span style="color:#ff0000;">src</span><span style="color:#0000ff;">="../../Scripts/extjs/ext-all-debug.js"</span><span style="color:#0000ff;">&#62;&#60;/</span><span style="color:#800000;">script</span><span style="color:#0000ff;">&#62;</span></pre>
<p>The order in which you include the JavaScript files is important.</p>
<p><em>Note: Please remember that it is essential to put all your css files in the head section of the page &#8211; this improves the loading of your page. All js files that are needed for the page rendering should also be put in the head, otherwise they should be put at the end of your page. I will talk more about this in a future blog post.</em></p>
<p>For the purpose of this sample application I will use the AdventureWorks database alongside with the Entity Framework for my data model. First we have to add the database into the App_Data folder and then create our data model in the Models folder. The Entity Framework will generate all the necessary entities and a context class and we are ready to write our data access code &#8211; I will write my LINQ queries against the database in the controller classes though you will not do this in a real world application. You would use for example the Repository pattern, put your data access logic in a separate assembly, maybe write your own services that will abstract away the business logic and inject them with some Dependency Injection framework, etc.</p>
<div id="attachment_63" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.wordpress.com/files/2009/11/ef_datamodel.png"><img class="size-full wp-image-63" title="Entity Framework Data Model" src="http://nraykov.wordpress.com/files/2009/11/ef_datamodel.png" alt="Entity Framework Data Model" width="600" height="414" /></a><p class="wp-caption-text">Entity Framework Data Model</p></div>
<p>Now that we have everything in place we can write an action method which would return a subset of employees:</p>
<pre style="overflow:auto;">[AcceptVerbs(HttpVerbs.Get)]
[ActionName(<span style="color:#006080;">"Employees"</span>)]
<span style="color:#0000ff;">public</span> JsonResult GetEmployees()
{
   <span style="color:#0000ff;">int</span> start = Convert.ToInt32(Request.QueryString[<span style="color:#006080;">"start"</span>]);
   <span style="color:#0000ff;">int</span> limit = Convert.ToInt32(Request.QueryString[<span style="color:#006080;">"limit"</span>]);

   <span style="color:#0000ff;">using</span> (AdventureWorksEntities dbContext = <span style="color:#0000ff;">new</span> AdventureWorksEntities())
   {
      var query = dbContext.Employees
                              .Include(<span style="color:#006080;">"Contact"</span>)
                              .OrderBy(emp =&#62; emp.EmployeeID);
      var result = (from emp <span style="color:#0000ff;">in</span> query
                                  .Skip(start).Take(limit).ToList()
                    select <span style="color:#0000ff;">new</span>
                    {
                       ID = emp.EmployeeID,
                       FirstName = emp.Contact.FirstName,
                       LastName = emp.Contact.LastName,
                       BirthDate = emp.BirthDate.ToShortDateString(),
                       HireDate = emp.HireDate.ToShortDateString(),
                       VacationHours = emp.VacationHours,
                       SickLeaveHours = emp.SickLeaveHours,
                       Email = emp.Contact.EmailAddress,
                       Phone = emp.Contact.Phone
                    }).ToList();

      <span style="color:#0000ff;">return</span> Json(<span style="color:#0000ff;">new</span> { data = result, totalCount = query.Count() }, JsonRequestBehavior.AllowGet);
   }
}</pre>
<p>Notice the <strong>AcceptVerbs </strong>attribute that the method is decorated with &#8211; it tells the framework that only GET requests are allowed to call the method through the <strong>HttpVerbs </strong>enumeration. This was the way to constrain the requests so far but in the new version of ASP.NET MVC there are some new handy attributes that you could use as well &#8211; <strong>HttpGet</strong>, <strong>HttpPost</strong>, <strong>HttpPut </strong>and <strong>HttpDelete </strong>which do the same thing. I am using the <strong>ActionName </strong>attribute to explicitly add a name for my action method so that I could have a nice URL schema for my actions and use the same name for different CRUD operations (I just need to use different verb for the requests).</p>
<p>In the method itself I create an instance of the database context and based on the parameters received from the grid I do paging with the LINQ extension methods Skip and Take. The interesting part is when the data is returned as a JSON &#8211; in ASP.NET MVC 1 the JSON method required a single parameter while now you have to pass an additional parameter of type JsonRequestBehavior. It is introduced for security reasons and you as a developer should explicitly decide whether or not to support GET requests. The problem is that if you return a response in the form of a JSON Array for a GET request it could be easily compromised, so it is suggested to wrap it inside a JSON object or do POSTs instead of that. You could read more about this in <a title="JSON Hijacking" href="http://haacked.com/archive/2009/06/25/json-hijacking.aspx" target="_blank">Phil Haack&#8217;s post</a>.</p>
<p>Next we need to write the JavaScript code that will instantiate our grid and fetch the data from the server:</p>
<pre style="font-size:small;color:black;font-family:Consolas,;overflow:auto;"><span style="color:#0000ff;">&#60;</span><span style="color:#800000;">script</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">="text/javascript"</span><span style="color:#0000ff;">&#62;</span>
   $(document).ready(<span style="color:#0000ff;">function</span> () {
      <span style="color:#0000ff;">var</span> store = <span style="color:#0000ff;">new</span> Ext.data.Store({
         proxy: <span style="color:#0000ff;">new</span> Ext.data.HttpProxy({
            url: <span style="color:#006080;">'Home/Employees'</span>,
            dataType: <span style="color:#006080;">'json'</span>,
            method: <span style="color:#006080;">'GET'</span>
         }),
         reader: <span style="color:#0000ff;">new</span> Ext.data.JsonReader({
            root: <span style="color:#006080;">'data'</span>,
            totalProperty: <span style="color:#006080;">'totalCount'</span>
         }, Ext.data.Record.create([
            { name: <span style="color:#006080;">'ID'</span>, mapping: <span style="color:#006080;">'ID'</span> },
            { name: <span style="color:#006080;">'FirstName'</span>, mapping: <span style="color:#006080;">'FirstName'</span> },
            { name: <span style="color:#006080;">'LastName'</span>, mapping: <span style="color:#006080;">'LastName'</span> },
            { name: <span style="color:#006080;">'BirthDate'</span>, mapping: <span style="color:#006080;">'BirthDate'</span> },
            { name: <span style="color:#006080;">'HireDate'</span>, mapping: <span style="color:#006080;">'HireDate'</span> },
            { name: <span style="color:#006080;">'VacationHours'</span>, mapping: <span style="color:#006080;">'VacationHours'</span> },
            { name: <span style="color:#006080;">'SickLeaveHours'</span>, mapping: <span style="color:#006080;">'SickLeaveHours'</span> },
            { name: <span style="color:#006080;">'Email'</span>, mapping: <span style="color:#006080;">'Email'</span> },
            { name: <span style="color:#006080;">'Phone'</span>, mapping: <span style="color:#006080;">'Phone'</span> }
         ]))
      });

      <span style="color:#0000ff;">var</span> grid = <span style="color:#0000ff;">new</span> Ext.grid.GridPanel({
         store: store,
         columns: [
            { header: <span style="color:#006080;">'ID'</span>, dataIndex: <span style="color:#006080;">'ID'</span>, hidden: <span style="color:#0000ff;">true</span> },
            { header: <span style="color:#006080;">'First Name'</span>, dataIndex: <span style="color:#006080;">'FirstName'</span>, width: 100 },
            { header: <span style="color:#006080;">'Last Name'</span>, dataIndex: <span style="color:#006080;">'LastName'</span>, width: 100 },
            { header: <span style="color:#006080;">'Birth Date'</span>, dataIndex: <span style="color:#006080;">'BirthDate'</span>, width: 100 },
            { header: <span style="color:#006080;">'Hire Date'</span>, dataIndex: <span style="color:#006080;">'HireDate'</span>, width: 100 },
            { header: <span style="color:#006080;">'Vacation Hours'</span>, dataIndex: <span style="color:#006080;">'VacationHours'</span>, width: 100 },
            { header: <span style="color:#006080;">'Sick Leave Hours'</span>, dataIndex: <span style="color:#006080;">'SickLeaveHours'</span>, width: 100 },
            { header: <span style="color:#006080;">'Email'</span>, dataIndex: <span style="color:#006080;">'Email'</span>, width: 200 },
            { header: <span style="color:#006080;">'Phone'</span>, dataIndex: <span style="color:#006080;">'Phone'</span>, width: 200 }
         ],
         renderTo: <span style="color:#006080;">'grid'</span>,
         width: 1000,
         autoHeight: <span style="color:#0000ff;">true</span>,
         bbar: <span style="color:#0000ff;">new</span> Ext.PagingToolbar({
            store: store,
            pageSize: 25,
            displayInfo: <span style="color:#0000ff;">true</span>,
            displayMsg: <span style="color:#006080;">'Displaying employees {0} - {1} of {2}'</span>,
            emptyMsg: <span style="color:#006080;">"No employees to display"</span>
         }),
         pageSize: 20,
         title: <span style="color:#006080;">'Employees'</span>
      });

      grid.getStore().load({ <span style="color:#0000ff;">params</span>: {
         start: 0,
         limit: 25
      }
   });
});
<span style="color:#0000ff;">&#60;/</span><span style="color:#800000;">script</span><span style="color:#0000ff;">&#62;</span></pre>
<p>When the DOM is ready to be manipulated I create a Store which will make the request to the server and use a JsonReader object which has all the necessary mappings in place to parse the data. Then an instance of the Grid is created with the store that was created in the previous step and columns which are mapped to the parsed JSON result object. That&#8217;s all you need to do &#8211; create these objects passing some configurations and you are ready to get your data. All the tricky parts of making an XmlHttpRequest, parsing the JSON, creating the HTML for the grid is done for you. Here is how the grid looks like when the application is run:</p>
<div id="attachment_78" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.wordpress.com/files/2009/11/ext_js_grid.png"><img class="size-full wp-image-78" title="Ext Js Grid" src="http://nraykov.wordpress.com/files/2009/11/ext_js_grid.png" alt="Ext Js Grid" width="600" height="382" /></a><p class="wp-caption-text">Ext Js Grid</p></div>
<p>This is a simple application in which I wanted to show you how to use Ext JS Grid to present data in a nice tabular fashion using ASP.NET MVC and Entity Framework. Here you could <a href="http://www.box.net/shared/f20o4ol724">download</a> the code for this app (I have not included the AdventureWorks database in order to keep the file size small, but you could download it from <a href="http://www.codeplex.com/MSFTDBProdSamples" target="_blank">here</a>).</p>
<p>In my next blog post I will show you how to write ASP.NET MVC HTML extension methods to include CSS and JavaScript files in your pages and how to instantiate some jQuery UI plugin widgets.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[@Lab This Week 11/27]]></title>
<link>http://goldmanalpha.wordpress.com/2009/11/27/lab-this-week-1127/</link>
<pubDate>Fri, 27 Nov 2009 22:30:56 +0000</pubDate>
<dc:creator>goldmanalpha</dc:creator>
<guid>http://goldmanalpha.wordpress.com/2009/11/27/lab-this-week-1127/</guid>
<description><![CDATA[Just Test – Nuff Said? Nah. Big discussion about unit testing.  Views ranged from 100% coverage is n]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h1>Just Test – Nuff Said? Nah.</h1>
<p>Big discussion about unit testing.  Views ranged from 100% coverage is necessary, to some code is not worth the trouble.  The 100% camp was hit with this rebuttal:</p>
<blockquote><p>How is the coverage measured?<br />
Is it just checking which code blocks ran during the test?<br />
What about covering different code paths?</p></blockquote>
<p>Everyone was in favor and there were some interesting insights including an example of “correctness by construction” in <a href="http://www.haskell.org/" target="_blank">Haskell</a>:</p>
<blockquote><p>…&#8221;correctness by construction&#8221; (aka &#8220;making illegal states unrepresentable&#8221;).  This approach relies on a rich type-system (and, at a deeper level, an interesting fact technically known as the &#8220;Curry-Howard isomorphism&#8221;).  Ideally, when this can be achieved you can completely discharge the need for a lot of unit tests (replacing sort of probabilistic certainty with actual certainty).</p></blockquote>
<p>Plenty of good links were sent and summarized:</p>
<blockquote><p><a href="http://channel9.msdn.com/posts/Peli/Experimental-study-about-Test-Driven-Development/" target="_blank">This study</a> found bug reductions of 40-90% with 15-25% coding time added.</p>
<p>Some recommend <a href="http://martinfowler.com/ieeeSoftware/beforeClarity.pdf" target="_blank">testability above clarity</a>.</p>
<p><a href="http://objectmentor.com/resources/articles/TestableJava.pdf" target="_blank">Guidelines on proper coding for testability (in Java)</a>.</p></blockquote>
<h1>Miscellany</h1>
<p>I heard some talk about an A team being formed to take on a project. I’d like to see the problem these guys can’t solve.</p>
<p>Check out <a href="http://www.huagati.com/dbmltools/" target="_blank">this interesting tool</a> for translating a data model into a class model with proper naming and casing using either Entity Framework or Linq2SQL.</p>
<p>All in all, a quiet week as expected.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[title]]></title>
<link>http://scriptforall.wordpress.com/2009/11/24/title-32/</link>
<pubDate>Tue, 24 Nov 2009 14:07:27 +0000</pubDate>
<dc:creator>kostland</dc:creator>
<guid>http://scriptforall.wordpress.com/2009/11/24/title-32/</guid>
<description><![CDATA[PC: Acer doubles Dell in the 3rd quarter &#8211; Actualits &#8211; ZDNet. Fr id=&#8221;; talkbackfor]]></description>
<content:encoded><![CDATA[PC: Acer doubles Dell in the 3rd quarter &#8211; Actualits &#8211; ZDNet. Fr id=&#8221;; talkbackfor]]></content:encoded>
</item>
<item>
<title><![CDATA[Coming Soon Entity Framework Won&rsquo;t Suck]]></title>
<link>http://goldmanalpha.wordpress.com/2009/11/19/entity-framework/</link>
<pubDate>Thu, 19 Nov 2009 14:08:41 +0000</pubDate>
<dc:creator>goldmanalpha</dc:creator>
<guid>http://goldmanalpha.wordpress.com/2009/11/19/entity-framework/</guid>
<description><![CDATA[I hear that EF in .Net 4.0 will be a bit better.  An experienced developer says: A lot of the bigges]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I hear that EF in .Net 4.0 will be a bit better.  An experienced developer says:</p>
<blockquote><p>A lot of the biggest issues I&#8217;ve had with EF … have been addressed in one way or another in the v2 that comes out with .NET 4.  Self-tracking entities, POCO objects as entities, persistence ignorance, etc. etc.  I don&#8217;t know how much they&#8217;ve improved the designer.  The v2 looks much, much better.  Generally, if you don&#8217;t see moving to .NET 4 in the medium term as likely, I would look seriously into nHibernate, but if .NET 4 is realistic, I would seriously consider EF v2.</p></blockquote>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Microsoft Loves Data at PDC 2009]]></title>
<link>http://scottrudy.wordpress.com/2009/11/19/microsoft-loves-data-at-pdc-2009/</link>
<pubDate>Thu, 19 Nov 2009 12:24:39 +0000</pubDate>
<dc:creator>Scott Rudy</dc:creator>
<guid>http://scottrudy.wordpress.com/2009/11/19/microsoft-loves-data-at-pdc-2009/</guid>
<description><![CDATA[I watched a good bit of the PDC 2009 webcasts last night and found there are some interesting techno]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I watched a good bit of the <a href="http://microsoftpdc.com/">PDC 2009</a> webcasts last night and found there are some interesting technologies coming out. I don’t think it comes as much of a surprise that Microsoft is cramming Azure and Silverlight down developer’s throats. There were also talks of IE 9 (don’t worry they are just starting development) and <a href="http://www.microsoft.com/visualstudio/en-us/products/2010/default.mspx">Visual Studio 2010</a>. In my opinion Visual Studio 2010 is a game changer in development if they can get the performance up and memory requirements down. The top feature in, in my opinion, is the historical debugging capability in <a href="http://msdn.microsoft.com/en-us/library/dd264915(VS.100).aspx">IntelliTrace</a>, which allows a snapshot call stack to be taken in a different environment and then allows a developer to open that snapshot and step through the source code right on their desktop.</p>
<p>All that aside, there seems to be an increased focus on data this year and a multitude of code name and product name changes. I want to provide an overview of my understanding of the recent items that were discussed at <a href="http://microsoftpdc.com/">PDC 2009</a> relating to data.</p>
<ul>
<li>Windows Azure Tables and Blobs are a way to store data in the cloud. When that wasn’t enough Microsoft moved to Azure SQL Data Services. This technology allowed users to store data in SQL tables and was extremely scalable. Apparently the public doesn’t care about scale because they want relational. So Microsoft has renamed the offering to <a href="http://www.microsoft.com/windowsazure/sqlazure/">SQL Azure</a>. The primary differences are that now you can actually use SQL Server Management Studio to connect using the (Tabular Data Stream) TDS protocol and you can use relational queries.</li>
<li>Oslo was a metadata framework for managing data and has now been boiled down to M and Quadrant and now falls under a larger umbrella of <a href="http://msdn.microsoft.com/en-us/data/ee461169.aspx">SQL Server Modeling Services</a>. Honestly I can’t quite see the compelling argument for this yet unless you are a DSL (domain specific language) designer.</li>
<li>Astoria was a REST based data access service. It was renamed to ADO.Net data services and recently changed to <a href="http://msdn.microsoft.com/en-us/data/bb931106.aspx">WCF data services</a>. The new name change also introduced <a href="http://blogs.msdn.com/astoriateam/archive/2009/11/17/breaking-down-data-silos-the-open-data-protocol-odata.aspx">OData</a>, which sounds like the new ADO.Net (yes, yet another <a href="http://blogs.msdn.com/data/archive/2006/12/05/data-access-api-of-the-day-part-i.aspx">data access technology</a>).</li>
<li><a href="http://pinpoint.microsoft.com/en-US/Dallas">Dallas</a> is a new data service from Microsoft intended to create a market place for data, the new commodity (I guess this is Microsoft’s answer to Apple’s iTunes and App Store). There are some public data sets available already for free. It seems the intention here is to enable innovation using data.</li>
<li><a href="http://www.getpivot.com/">Pivot</a> from Microsoft labs was one of the more compelling things I saw. It is essentially a new Internet browser that has an extension for understanding another new data format called Collection XML (cxml). The viewer uses Silverlight and <a href="http://www.youtube.com/watch?v=BAVeQImW_Zc">DeepZoom</a> to visualize data.</li>
<li><a href="http://msdn.microsoft.com/en-us/data/cc298428.aspx">LINQ to SQL</a> was a compelling technology that abstracted developer from writing T-SQL code by using an ORM (object-relational mapper). However, it seems tying this technology to SQL Server was not popular with the real world and Microsoft has been strongly advising against using it. In the 4.0 version of the .Net framework Microsoft placed this technology within the <a href="http://msdn.microsoft.com/en-us/data/aa937723.aspx">ADO.Net Entity Framework</a> (EF) and calls it “Direct Mapping”. The EF also supports mapping at a more abstract level using an <a href="http://msdn.microsoft.com/en-us/library/bb387122.aspx">Entity Data Model</a> (EDM) and a raw schema, should that be desired.</li>
</ul>
<div style="text-align:center;font-style:italic;font-family:verdana,arial;font-size:.8em;">Copyright © Scott P. Rudy 2009 All Rights Reserved</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Voyage vers MVC 2 et Entity Framework 2 : &eacute;tape 2 on quitte le port doucement&hellip;.]]></title>
<link>http://yoannr.wordpress.com/2009/11/19/voyage-vers-mvc-2-et-entity-framework-2-tape-2-on-quitte-le-port-doucement/</link>
<pubDate>Thu, 19 Nov 2009 09:15:07 +0000</pubDate>
<dc:creator>yoannr</dc:creator>
<guid>http://yoannr.wordpress.com/2009/11/19/voyage-vers-mvc-2-et-entity-framework-2-tape-2-on-quitte-le-port-doucement/</guid>
<description><![CDATA[Avant de se lancer dans des développements un peu trop compliqué, je voudrais savoir un peu comment ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Avant de se lancer dans des développements un peu trop compliqué, je voudrais savoir un peu comment marche la chose, au moins dans ses grandes lignes, et comment je vais pouvoir en tirer parti.</p>
<h2>Entity Framework</h2>
<p>&#160;</p>
<p>Le modele edmx ( il va falloir que je me renseigne sur les termes avant la fin, moi…) me génère mes objets tout seul. ca j’apprécie beaucoup. je me retrouve donc avec un objet comme suit ( en fait c’est beaucoup plus long, mais j’ai décidé de me retreindre à l’essentiel) :</p>
<p><em>[EdmEntityTypeAttribute(NamespaceName="Localisation", Name="Culture")]<br />
[Serializable()]<br />
[DataContractAttribute(IsReference=true)]<br />
public partial class Culture : EntityObject<br />
{<br />
    public global::System.Int32 Id {get; set;}<br />
    public global::System.String Language {get; set;}<br />
    public global::System.String Country {get; set;}<br />
}</em></p>
<p>Pour l’instant, je ne regarderais pas plus avant ce qu&#8217; il y a dedans.</p>
<p>Et je ne m’attarderais pas non plus sur toutes les fonctions possibles contenues le modele edmx, mais par contre je vais les utiliser dans un classe RepositoryCulture.</p>
<p><em>public class CultureRepository: ICultureRepository<br />
   { </em></p>
<p><em>       LocalisationContainer container ; </em></p>
<p><em>       public CultureRepository(string connectionstring)<br />
       {<br />
           container = new LocalisationContainer(connectionstring);<br />
       } </em></p>
<p><em>       // Query Methods<br />
       public IQueryable&#60;Culture&#62; FindAllCulture()<br />
       {<br />
           return  container.T_Culture;<br />
       }<br />
       public Culture FindCulture(int CultureId)<br />
       {<br />
           var culture=  from c in FindAllCulture()<br />
                          where c.Id == CultureId<br />
                           select c;<br />
           return culture.SingleOrDefault();<br />
       } </em></p>
<p><em>       // Insert/Delete<br />
       public void AddCulture(Culture c)<br />
       {<br />
           container.T_Culture.AddObject(c);<br />
           container.SaveChanges();<br />
       }<br />
       public void DeleteCulture(Culture c)<br />
       {<br />
           container.T_Culture.DeleteObject(c);<br />
           container.SaveChanges();<br />
       } </em></p>
<p><em>       // Persistence<br />
       public void Save()<br />
       {<br />
           container.SaveChanges();<br />
       }<br />
   }</em></p>
<p>Cette dernière va me permettre de manipuler mon edmx, de façon sereine. Mais cela veut donc dire que je vais utiliser une interface afin de me préserver d’un éventuel changement d’humeur de ma part ( je pourrais avoir envie d’essayer Nhibernate par exemple, plus tard…  grrr…)</p>
<p><em>public interface ICultureRepository<br />
    {<br />
    // Query Methods<br />
    IQueryable&#60;Culture&#62; FindAllCulture();<br />
    Culture FindCulture(int CultureId); </em></p>
<p><em>    // Insert/Delete<br />
    void AddCulture(Culture c);<br />
    void DeleteCulture(Culture c);<br />
    // Persistence<br />
    void Save(); </em></p>
<p><em>    }</em></p>
<p>&#160;</p>
<p>Je dispose donc maintenant d’une méthode conviviale pour jouer avec mes données de Culture. Passons au coté MVC…</p>
<h3>MVC</h3>
<h4>l’acces aux donnés</h4>
<p>De la même façon, que je suis parti sur un concept simple pour le coté Entity Framework, je ferais de même pour ma première approche de MVC.</p>
<p>La première chose que je veux faire, c’est de pouvoir accéder aux donnés facilement dans mon application MVC, je vais donc poursuivre le travail effectué plus avant, et généraliser ma façon d’accéder aux infos. Pour ce faire, je vais utilser un composant d’injection de dépendance / Inversion de Contrôle  nommé <a href="http://structuremap.sourceforge.net/Default.htm" target="_blank">StructureMap</a></p>
<p>Je ne susi réellement pas un expert de ce genre de composé, j ai donc repiqué beaucoup d’idée a un tutorial MVC de microsoft. Mais voilà ce que j’ai pu en tirer pour mon cas présent.</p>
<p>dans mon application_start , j’ai rajouté</p>
<blockquote><p><em>        BootStrapper.ConfigureStructureMap(); </em></p></blockquote>
<p><em>           ControllerBuilder.Current.SetControllerFactory(<br />
               new StructureMapControllerFactory()<br />
               );</em></p>
<p>Cela me permet d’initialiser le composant. la classe BootStrapper consiste en deux lignes :</p>
<p><em>public class BootStrapper<br />
   {<br />
       public static void ConfigureStructureMap()<br />
       {<br />
           StructureMapConfiguration.AddRegistry(new DBServiceRegistry()); <br />
           StructureMapConfiguration.AddRegistry(new StorefrontRegistry());<br />
       }<br />
   }</em></p>
<p>Et la classe DBServiceReigistry, va me permettre d’instancier ma conenction à la bonne base pour entity :</p>
<p><em>public class DBServiceRegistry : Registry<br />
    {<br />
        public string ConnectionString<br />
        {<br />
            get<br />
            {<br />
                if (WebConfigurationManager.ConnectionStrings["Application"]==null)<br />
                    throw new InvalidOperationException(&#8220;Conenction string Application cannot be null.&#8221;);<br />
                if (string.IsNullOrEmpty(WebConfigurationManager.ConnectionStrings["Application"].ToString()))<br />
                    throw new InvalidOperationException(&#8220;Connection string Application cannot be empty.&#8221;); </em></p>
<p><em>                return WebConfigurationManager.ConnectionStrings["Application"].ToString();<br />
            }<br />
        } </em></p>
<p><em>        protected override void configure()<br />
        { </em></p>
<p><em>            ForRequestedType&#60;System.Data.EntityClient.EntityConnection&#62;()<br />
                .TheDefaultIs(() =&#62; new System.Data.EntityClient.EntityConnection(ConnectionString))<br />
                .CacheBy(InstanceScope.Hybrid); </em></p>
<p><em>        }<br />
    }</em></p>
<p>tandis que StoreFrontRegistryx lui cataloguera, les différents repository que je peux avoir et instanciera la bonne classe.</p>
<p><em>public class StorefrontRegistry : Registry<br />
    {<br />
        protected override void configure()<br />
        { </em></p>
<p><em>            #region repository<br />
            ForRequestedType&#60;ICultureRepository&#62;()<br />
              .TheDefaultIsConcreteType&#60;CultureRepository&#62;(); </em></p>
<p><em>            ForRequestedType&#60;ILocalisationRepository&#62;()<br />
              .TheDefaultIsConcreteType&#60;LocalisationRepository&#62;();<br />
            #endregion<br />
        }<br />
    }</em></p>
<p>Pour l’instant, j’utilise une autre classe StructureMapControllerFactory, mais je n’ai pas encore pris le temps de changer quelque chose à l’intérieur, le besoin ne s’en est pas fait sentir tout du moins.</p>
<h4>les routes</h4>
<p>Pour mes routes je ne me suis pas trop embêté pour l’instant, et j ‘ai tapé dans le simple et efficace. J’ai codé en dur Localisation/Culture afin de faire un différence significative avec ce qui pourrait arrivé ensuite :</p>
<p>&#160;</p>
<p><em>public static void RegisterRoutes(RouteCollection routes)<br />
        {<br />
            routes.IgnoreRoute(&#8220;{resource}.axd/{*pathInfo}&#8221;); </em></p>
<p><em>            routes.MapRoute(<br />
                &#8220;home&#8221;,                                                  // Route name<br />
                &#8220;home/{controller}/{action}/{id}&#8221;,                       // URL with parameters<br />
                new { controller = &#8220;Home&#8221;, action = &#8220;Index&#8221;, id = &#8220;&#8221; }   // Parameter defaults<br />
            ); </em></p>
<p><em>            routes.MapRoute(<br />
               &#8220;localisation&#8221;,                                              // Route name<br />
               &#8220;localisation/culture/{action}/{id}&#8221;,                        // URL with parameters<br />
                new { controller = &#8220;Culture&#8221;, action = &#8220;Index&#8221;, id = &#8220;&#8221; }   // Parameter defaults<br />
           ); </em></p>
<p><em>        }</em></p>
<p>Par ailleurs avant d’aller plus loin , j ai installé un autre composant RouteDebug.dll qui me permet de debugger mes routes, je pense que tôt ou tard, j’en aurais besoin.</p>
<p>Pour ce faire, j’ai rajouter mais commenté pour le moment l’instruction suivante :</p>
<p>          <em>// ROUTES<br />
           RegisterRoutes(RouteTable.Routes);<br />
           //uncomment this line for route debugging<br />
           //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);</em></p>
<p>On peut voir dans ma route que j’instancie :</p>
<p><em>       new { controller = &#8220;Culture&#8221;, action = &#8220;Index&#8221;, id = &#8220;&#8221; }  </em></p>
<p>Ce faisant, j’instancie un contrôle nommé Culture.</p>
<h4>le controller</h4>
<p>Rien de plus simple que ce controller. Mais tout d’abord, faire attention à son vrai nom CultureController. C’est important afin que MVC ne se mélange pas les pinceaux.</p>
<p>Ensuite détaillons le controller :</p>
<p><span style="text-decoration:underline;">son constructeur :</span></p>
<p><em>#region constructor </em></p>
<p><em>       public CultureController(ICultureRepository repository)<br />
       {<br />
           _repository = repository;<br />
           if (_repository == null)<br />
               throw new Exception(&#8220;Repository cannot be null&#8221;);<br />
       } </em></p>
<p><em>       #endregion</em></p>
<p>Il prend en entrée un ICultureRepository  qui sera instancié par StructureMap avec la bonne classe.</p>
<p>et ensuite correspondant à l’ {action} de ma route :</p>
<p><em>      // GET: /Localisation/Culture/Index ou /Localisation/Culture<br />
        public ActionResult Index()<br />
        {<br />
            IQueryable&#60;Culture&#62; cultures = _repository.FindAllCulture();<br />
            return View(&#8220;Index&#8221;, cultures);<br />
        }</em></p>
<p>Suivant l’url /Localisation/Culture/Index ou /Localisation/Culture, j’appellerais le Controller Culture et j’effectuerais l’action Index, qui me renverra la vue Index.</p>
<p>La vue Index prend en parametre un IQueryable&#60;Cultures&#62;, que je vais chercher au moment ou j’en ai besoin.</p>
<p>Cela fonctionne de la même facon pour les autres actions, avec un petit détail à voir, à savoir la méthode utilisé pour appeler l’url qui permettra sur la même Url De procéder à plusieurs actions différentes :</p>
<p><em>public ActionResult Details(int id)<br />
public ActionResult Create()</em></p>
<p><em>[AcceptVerbs(HttpVerbs.Post)]<br />
public ActionResult Create(FormCollection collection)</em></p>
<p><em>[AcceptVerbs(HttpVerbs.Get)]<br />
public ActionResult Edit(int id)</em></p>
<p><em>[AcceptVerbs(HttpVerbs.Post)]<br />
public ActionResult Edit(int id, FormCollection collection)</em></p>
<p><em>[AcceptVerbs(HttpVerbs.Get)]<br />
public ActionResult Delete(int id)</em></p>
<p>Sur ce , il n’ y a plus qu’à créer les vues correspondantes</p>
<h4>les Views</h4>
<p>Personnellement, et pour le début, je ne me suis pas embêté, et j’ai pris l’assistant de visual studio pour les créer.  J’ai donc créé un répertoire Culture dans Views. Ceci est aussi important pour MVC.</p>
<p>Je pense qu il doit y avoir un moyen de changer ce paramètre par défaut , mais ce sera l’occasion de plus amples investigations.</p>
<p>Voilà ,c’est tout pour aujourd’hui. Bon c’est bien évidemment hyper débutant comme approche, mais c’Est ce que je suis, et je me disais que d’autres pourraient être intéressé par mon cheminement personnel, si jamais il y avait des amateurs de MVC et d’entity framework dans les parages!</p>
<p>La suite la semaine prochaine,</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Voyage vers MVC 2 et Entity Framework 2 :                &eacute;tape 1 on pr&eacute;pare le bateau et on  largue les amarres]]></title>
<link>http://yoannr.wordpress.com/2009/11/18/voyage-vers-mvc-2-et-entity-framework-2-tape-1-on-prpare-le-bateau-et-on-largue-les-amarres/</link>
<pubDate>Wed, 18 Nov 2009 15:23:22 +0000</pubDate>
<dc:creator>yoannr</dc:creator>
<guid>http://yoannr.wordpress.com/2009/11/18/voyage-vers-mvc-2-et-entity-framework-2-tape-1-on-prpare-le-bateau-et-on-largue-les-amarres/</guid>
<description><![CDATA[L’objectif que je me fixe dans les jours qui viennent est de réaliser une petite application de loca]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>L’objectif que je me fixe dans les jours qui viennent est de réaliser une petite application de localisation en ASP.net et MVC. Il s’agit pour moi surtout de me familiariser avec ces techniques, et peut être que je pourrais vous emmener avec moi sur un petit bout de chemin, qui sait?</p>
<p>Tout d’abord le but, je vais m’exprimer avec les mots que je connais a savoir ceux de l’univers webform: Avoir une librairie de contrôle qui accepteront un clé (localisationKey) et un langage. Cette clé possède une date de départ et une date de fin. Et associé à cette clé, je veux avoir un article (LocalisationItem) qui lui contiendra le texte a afficher en fonction du langage. Cela permettra de pouvoir aficher un texte en plusieurs langues et qui pourra changer aussi en fonction de la date.</p>
<p>Bref, rien de bien compliqué, surtout que j’ai déjà fait tout ca en webform. Il s’agit aussi pour moi, de voir l’effort à fournir pour transoposer vers le support MVC.net du travail déjà fait en webform.</p>
<p>Dernière petite précision, l’intérêt va être aussi d’utiliser Entity framework de façon à générer ma base de données à partir du modèle.</p>
<p>Les outils à ma disposition :</p>
<ul>
<li>Visual Studio 2010</li>
<li>Visual Studio 2005 expresse édition</li>
</ul>
<p>Tout d’abord mon premier schéma de données :</p>
<p><a href="http://yoannr.files.wordpress.com/2009/11/mvc1.gif"><img style="display:inline;border:0;" title="MVC1" src="http://yoannr.files.wordpress.com/2009/11/mvc1_thumb.gif?w=240&#038;h=105" border="0" alt="MVC1" width="240" height="105" /></a></p>
<p>Comme vous pouvez le constater, je pars du principe que je vais avoir des groupes qui contiendront des  groupes enfants, ou et des clés.</p>
<p>Et à chacune de ces clés, j’associe un item.</p>
<p>Lors de la création de mon schéma j’ai pris soin de spécifier pour chacun des id , la propriété StoreGeneratedPAttern=Identity. Cela me permet d’avoir un champ auto incrémenté du coté de ma base de données.</p>
<p>Du coté de ma solution, je m’oriente vers différents projets :</p>
<ul>
<li>site MVC</li>
<li>Data</li>
<li>Services</li>
<li>Test</li>
</ul>
<p>Tout ce ci n’est évidemment qu’une première approche, au fur et á mesure de l’avancée du projet j’affinerais un peu tout ca.</p>
<p>Voici le projet utilisé actuellement : <a href="http://dl.free.fr/bw9mru0KX" target="_blank">solution VS 2010</a></p>
<p>Suite dans l’étape 2&#8230;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[In Memory of Linq2SQL - 2006 - 2008 - RIP]]></title>
<link>http://goldmanalpha.wordpress.com/2009/11/16/in-memory-of-linq2sql-2006-2008-rip/</link>
<pubDate>Mon, 16 Nov 2009 14:53:49 +0000</pubDate>
<dc:creator>goldmanalpha</dc:creator>
<guid>http://goldmanalpha.wordpress.com/2009/11/16/in-memory-of-linq2sql-2006-2008-rip/</guid>
<description><![CDATA[I was doing a lot of Linq2SQL recently and it was easy and convenient – I’d highly recommend it. Exc]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I was doing a lot of <a href="http://www.infoq.com/news/2008/11/DLINQ-Future" target="_blank">Linq2SQL</a> recently and it was easy and convenient – I’d highly recommend it. Except for the fact that its now obsolete. Linq2SQL is being <a href="http://codebetter.com/blogs/david.hayden/archive/2008/10/31/linq-to-sql-is-dead-read-between-the-lines.aspx">tossed aside</a> in favor of Entity Framework, which is not as lightweight or simple <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> . I would look into <a href="https://www.hibernate.org/343.html" target="_blank">NHibernate</a> from what I’ve read of <a href="http://discuss.joelonsoftware.com/default.asp?joel.3.723453.24" target="_blank">Entity Framework</a>.</p>
<p>In another version or two Entity Framework may get more of Linq2SQL’s simplicity and ease of use. Oh joy.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[ LInria inaugurates a research centre on the free software ]]></title>
<link>http://scriptforall.wordpress.com/2009/11/15/linria-inaugurates-a-research-centre-on-the-free-software/</link>
<pubDate>Sun, 15 Nov 2009 17:15:55 +0000</pubDate>
<dc:creator>kostland</dc:creator>
<guid>http://scriptforall.wordpress.com/2009/11/15/linria-inaugurates-a-research-centre-on-the-free-software/</guid>
<description><![CDATA[L `national research institute in data processing and automatic, Inria, comes D `to announce the occ]]></description>
<content:encoded><![CDATA[L `national research institute in data processing and automatic, Inria, comes D `to announce the occ]]></content:encoded>
</item>
<item>
<title><![CDATA[Entity Framework - Partial Commit of Data]]></title>
<link>http://microdotsagamedev.wordpress.com/2009/11/12/entity-framework-partial-commit-of-data/</link>
<pubDate>Thu, 12 Nov 2009 13:01:27 +0000</pubDate>
<dc:creator>microdotsagamedev</dc:creator>
<guid>http://microdotsagamedev.wordpress.com/2009/11/12/entity-framework-partial-commit-of-data/</guid>
<description><![CDATA[I recently answered a question on StackOverflow regarding partial commits. The poster was refering t]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I recently answered a question on StackOverflow regarding partial commits. The poster was refering to two contexts being used to isolate changes from the ones he / she actually wanted to commit. I disagree with using two contexts when the same can be achieved with one. Below is a simple example of reverting all objects of a certain type to their original state, if you were to call a SaveChanges() on the context after this &#8211; only the remaining objects in added or changed state will commit &#8211; a partial commit. Very similar to another post I&#8217;ve pressed before &#8211; but hey&#8230; someone may search for this one <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<pre style="padding-left:30px;"><code>foreach (System.Data.Objects.ObjectStateEntry x in
MyEntity.ObjectStateManager.GetObjectStateEntries(EntityState.Added))
// or modified for that matter.
{
   if (x.EntityKey != null)
   {  
      if (x.Entity is MyClass)
      // look haven't tested this code, merely example and may have typo's
      {
         MyClass tmpObject = (MyClass)x.Entity;
         MyEntity.Refresh(RefreshMode.StoreWins, x);
      }
   }
}
</code></pre>
<p>There is a lot of control available to you if you track the items you&#8217;re wanting to &#8220;partial&#8221; commit. The ones you&#8217;re wanting to revert to original state or discard can be reverted or even removed completely from the context.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Does Entity Framework/LINQ to SQL Implment ITypedList?]]></title>
<link>http://devmanic.wordpress.com/2009/11/11/does-entity-frameworklinq-to-sql-implment-itypedlist/</link>
<pubDate>Wed, 11 Nov 2009 18:27:59 +0000</pubDate>
<dc:creator>Drew</dc:creator>
<guid>http://devmanic.wordpress.com/2009/11/11/does-entity-frameworklinq-to-sql-implment-itypedlist/</guid>
<description><![CDATA[As I looked into the ITypedList interface I realized that perhaps everything I needed was already im]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>As I <a href="http://devmanic.wordpress.com/2009/11/11/binding-grids-to-hierarchical-data-using-the-itypedlist-interface/">looked into the ITypedList interface</a> I realized that perhaps everything I needed was already implemented as my business objects are generated by Linq-To-Sql? The answer turns out to be &#8220;sort-of&#8221;.</p>
<blockquote><p>I&#8217;m taking a peek at both the Entity Framework and LINQ to SQL, and while I like the systems (and of course the LINQ integration) I&#8217;m a little skeptical on the data-binding aspect. I&#8217;ve taken query results and inspected them, and they don&#8217;t appear to implement the standard .NET list-binding interfaces (IBindingList, and more importantly ITypedList), leading me to believe that binding them to a grid (or anything else) is going to use reflection to get/set my entity properties. This seems like a comparatively expensive operation, especially when all of the code is generated anyway and could implement the interfaces.</p></blockquote>
<p>via <a href="http://stackoverflow.com/questions/766540/does-entity-framework-linq-to-sql-data-binding-use-reflection">Does Entity Framework/LINQ to SQL Data Binding use reflection? &#8211; Stack Overflow</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Entity framework 4 - Part 2 - Relationships between non-public members]]></title>
<link>http://daniel.wertheim.se/2009/11/10/entity-framework-4-relationships-between-non-public-members/</link>
<pubDate>Tue, 10 Nov 2009 21:17:51 +0000</pubDate>
<dc:creator>Daniel Wertheim</dc:creator>
<guid>http://daniel.wertheim.se/2009/11/10/entity-framework-4-relationships-between-non-public-members/</guid>
<description><![CDATA[Part 1 &#8211; Getting started Part 3 &#8211; Adding pluralization support Ok, the mission of this p]]></description>
<content:encoded><![CDATA[Part 1 &#8211; Getting started Part 3 &#8211; Adding pluralization support Ok, the mission of this p]]></content:encoded>
</item>
<item>
<title><![CDATA[EDMX Issues With Visual Studio 2010 Beta 1 to Beta 2]]></title>
<link>http://devmanic.wordpress.com/2009/11/10/edmx-issues-with-visual-studio-2010-beta-1-to-beta-2/</link>
<pubDate>Tue, 10 Nov 2009 20:47:59 +0000</pubDate>
<dc:creator>Drew</dc:creator>
<guid>http://devmanic.wordpress.com/2009/11/10/edmx-issues-with-visual-studio-2010-beta-1-to-beta-2/</guid>
<description><![CDATA[Scenario: Important meeting! Too much coffee! Bad lighting! In walks the killer! Wait&#8230; No, tha]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Scenario: Important meeting! Too much coffee! Bad lighting! In walks the killer! Wait&#8230;</p>
<p>No, that&#8217;s wrong. In walks Visual Studio 2010 Beta 2 with an inability to open an EDMX created with Visual Studio 2010 Beta 1, asking if I&#8217;d like to open the file in an XML editor. Ack! A previously printed paper diagram (for the meeting) and a bit of time later I resolved the differences between my EDMX and a test EDMX created with Beta 2.</p>
<ol>
<li>The Schema tag,next item after &#60;edmx:StorageModels&#62;, had the correct xmlns property but was missing entirely the xmlns:store property. Adding xmlns:store=&#8221;http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator&#8221; was required.</li>
<li>The Schema tag,next item after &#60;edmx:ConceptualModels&#62;, had the correct xmlns property but was missing entirely the xmlns:annotation property. Adding xmlns:annotation=&#8221;http://schemas.microsoft.com/ado/2009/02/edm/annotation&#8221; was required.</li>
<li>Changing all &#8220;store:&#8221; prefixed properties of elements within  ConceptualModels to be &#8220;annotation:&#8221; prefixed.</li>
<li>Swore at Microsoft a little for giving me the &#8220;prividledge&#8221; of hand-editing a 2400 line xml file.</li>
</ol>
<p>A save and compile later I could open my diagram and proceed. Hope that helps!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Entity framework 4 - Part 1 - CTP 2 - Clean code with POCO entities]]></title>
<link>http://daniel.wertheim.se/2009/11/09/entity-framework-4-ctp-2-clean-code-with-poco-entities/</link>
<pubDate>Mon, 09 Nov 2009 21:31:55 +0000</pubDate>
<dc:creator>Daniel Wertheim</dc:creator>
<guid>http://daniel.wertheim.se/2009/11/09/entity-framework-4-ctp-2-clean-code-with-poco-entities/</guid>
<description><![CDATA[Part 2 &#8211; Relationships between non public members Part 3 &#8211; Adding pluralization support ]]></description>
<content:encoded><![CDATA[Part 2 &#8211; Relationships between non public members Part 3 &#8211; Adding pluralization support ]]></content:encoded>
</item>
<item>
<title><![CDATA[Two flavors of DDD]]></title>
<link>http://rogeralsing.com/2009/11/08/two-flavors-of-ddd/</link>
<pubDate>Sun, 08 Nov 2009 12:40:32 +0000</pubDate>
<dc:creator>Roger Alsing</dc:creator>
<guid>http://rogeralsing.com/2009/11/08/two-flavors-of-ddd/</guid>
<description><![CDATA[I have been trying to practice domain driven design for the last few years. During this time, I have]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I have been trying to practice domain driven design for the last few years.<br />
During this time, I have learnt that there are almost as many ways to implement DDD as there are practitioners.</p>
<p>After studying a lot of different implementations I have seen two distinct patterns.</p>
<p>I call the first pattern <strong>&#8220;Aggregate Graph&#8221;</strong>:</p>
<p>When applying aggregate graphs, you allow members of one aggregate to have direct associations to another aggregate.<br />
For example, an &#8220;Order&#8221; entity which is part of a &#8220;Order aggregate&#8221; might have a &#8220;Customer&#8221; property which leads directly to a &#8220;Customer&#8221; entity that is part of a &#8220;Customer aggregate&#8221;.</p>
<p> <img class="alignnone size-full wp-image-677" title="aggregate-graph" src="http://rogeralsing.wordpress.com/files/2009/11/aggregate-graph.gif" alt="aggregate-graph" width="583" height="362" /></p>
<p>According to Evans book this is completely legal, any member of an aggregate may point to the root of any other aggregate.<br />
Evans is very clear on the matter that aggregate root identities are global while identity of non root entities are local to the aggregate itself.</p>
<p>The opposite pattern would be what I call <strong>&#8220;Aggregate Documents&#8221;</strong>:</p>
<p>Here the aggregates never relate _directly_ to other aggregate roots.<br />
Instead, the associations may be designed as &#8220;snapshots&#8221; where you store light weight value object clones of the related aggregate roots.<br />
An &#8220;Order&#8221; entity would have a &#8220;Customer&#8221; property which leads to a &#8220;CustomerSnapshot&#8221; value object instead of a Customer entity.<br />
This way each aggregate instance becomes more of a free-floating document.</p>
<p><img class="alignnone size-full wp-image-679" title="aggregate-document" src="http://rogeralsing.wordpress.com/files/2009/11/aggregate-document.gif" alt="aggregate-document" width="583" height="648" /></p>
<p>Since I have been applying both of these patterns, I will try to highlight the pros and cons of them in the rest of this post.</p>
<h2>Aggregate Graph</h2>
<p>The Aggregate Graph pattern is the approach I used when I first started doing DDD and I think that it is the most common way to implement DDD.<br />
Since I was an O/RM developer (NPersist) this felt very natural to me, I could design my object graph in our design tool and then draw a few boxes on top of it and claim that those were my aggregates.<br />
I most often used eager load inside the aggregates and lazy load between aggregates in order to avoid that the entire database was fetches when one aggregate instance was loaded.</p>
<p>This had a very nice &#8220;OOP&#8221; feel to it, I was working with objects and associations and I could ignore that there even was a database involved.</p>
<p>My &#8220;Repositories&#8221; were mere windows into my object graph, I could ask a repository to give me one or more aggregate roots and from those object I could pretty much navigate to any other object in the graph due to the spider web nature of the aggregate graph.</p>
<p><img class="alignnone size-full wp-image-680" title="repository-window" src="http://rogeralsing.wordpress.com/files/2009/11/repository-window.gif" alt="repository-window" width="448" height="402" /></p>
<p>The pros of this approach is that it is easy to understand, you design your domain model just like any other class model.<br />
It also works very well with O/R mappers, features like Lazy Load and Dirty Tracking makes it all work for you.</p>
<p>However, there are a few problems with this approach too.<br />
Firstly, Lazy Load in O/R mappers is an implicit feature, there is no way for a developer to know at what point he will trigger a roundtrip to the database just by reading the code.<br />
It always looks like you are traversing a fully loaded object graph while you are in fact not.<br />
This often leads to severe performance problems if your development team don&#8217;t fully understand this.</p>
<p>I have seen reports over this kind domain models where the implicit nature of Lazy Load have caused some 700 round-trip to the database in a single web page.</p>
<p>This is what you get when you try to solve an explicit problem in an implicit way.</p>
<p>If you are going to use Lazy Load, make sure your team understands how it works and where you use it.</p>
<p>Another problem with this approach arise when you need to fill your entities with data from multiple sources.<br />
Many of the applications I build nowadays relies on data from multiple sources, it could be a combination of services and internal databases.</p>
<p>When using Lazy Load to get related aggregates, there is no natural point where you can trigger calls to the other data sources and fill additional properties.<br />
You will most likely have to hook into your O/R mapper in order to intercept a lazy load and call the services from there.<br />
nowadays, I mostly use the second approach, Aggregate Documents.</p>
<h2>Aggregate Document</h2>
<p>Aggregate Document approach is much more explicit in its design.<br />
For example, if you want to find the orders for a specific customer;<br />
Instead of navigating the &#8220;Orders&#8221; collection of &#8220;Customer&#8221;, you will have to call a &#8220;FindOrdersByCustomer&#8221; query on the &#8220;OrderRepository&#8221;.</p>
<p>While I do agree that this looks less object oriented than the first approach, this allows developers to reason about the code in a different way.<br />
They can see important design decisions and hopefully avoid pitfalls like ripple loading.</p>
<p>Another benefit is that since you only work with islands of data, you can now aggregate data from multiple sources much easier.<br />
You can simply let your repositories aggregate the data into your entities.<br />
<em>(If you do it inside the actual repository or let the repository use some data access class that does it for it is up to you)</em><br />
<img class="alignnone size-full wp-image-688" title="repo-prism" src="http://rogeralsing.wordpress.com/files/2009/11/repo-prism.gif" alt="repo-prism" width="458" height="140" /><br />
You don&#8217;t have to hook into any O/RM infrastructure since you no longer rely on lazy load between aggregates.</p>
<p>Personally I use eager load inside my aggregates, that is, I fetch &#8220;Order&#8221; and &#8220;Order Detail&#8221; together as a whole.<br />
A side effect of this is that since I don&#8217;t use Lazy Load between aggregates and don&#8217;t use Lazy Load inside my aggregates, my need for O/R mapping frameworks drops.<br />
I can apply this design without using a full-fledged O/R mapper framework.<br />
I&#8217;m not saying that you should avoid O/R mapping, just that it is much easier to apply this pattern if you can&#8217;t use an O/R mapper for some reason.</p>
<p>This also makes it easier to expose your domain model in an SOA environment.<br />
You can easily expose your entities or DTO versions of them in a service.</p>
<p>Lazy Load and services don&#8217;t play that well together.</p>
<p>Maybe it looks like I dislike the first approach, this is not the case, I may very well consider it in a smaller project where there is just one data source and where the development team is experienced with O/R mapping.<br />
You can also create hybrids of the two approaches;<br />
e.g. In Jimmy Nilsson&#8217;s book &#8220;Applying Domain Driven Design and Patterns&#8221; there are examples where an &#8220;Order&#8221; aggregate have a direct relation to the &#8220;Product&#8221; aggregate while the same &#8220;Order&#8221; aggregate uses snapshots instead of direct references to the &#8220;Customer&#8221; aggregate.</p>
<p>Snapshots also comes with the benefit of allowing you to store historical data.<br />
The snapshot can for example store both the CustomerId and the name of the customer at the time the order was placed.</p>
<p>Thats all for now.</p>
<p>//Roger</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[title]]></title>
<link>http://scriptforall.wordpress.com/2009/11/08/title-23/</link>
<pubDate>Sun, 08 Nov 2009 09:32:13 +0000</pubDate>
<dc:creator>kostland</dc:creator>
<guid>http://scriptforall.wordpress.com/2009/11/08/title-23/</guid>
<description><![CDATA[Russia opens an antitrust enqute against Microsoft &#8211; Actualits &#8211; ZDNet. Fr Plays vid]]></description>
<content:encoded><![CDATA[Russia opens an antitrust enqute against Microsoft &#8211; Actualits &#8211; ZDNet. Fr Plays vid]]></content:encoded>
</item>
<item>
<title><![CDATA[Entity Framework assications (Independent vs FK)]]></title>
<link>http://amiraryani.wordpress.com/2009/11/08/entity-framework-assications-independent-vs-fk/</link>
<pubDate>Sun, 08 Nov 2009 05:42:08 +0000</pubDate>
<dc:creator>Amir Aryani</dc:creator>
<guid>http://amiraryani.wordpress.com/2009/11/08/entity-framework-assications-independent-vs-fk/</guid>
<description><![CDATA[Entity Framework association is a different concept to FKs in the database schema.  Supporting or no]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Entity Framework association is a different concept to FKs in the database schema.  Supporting or not supporting the Schema FKs has been a topic for debate in the community until now. Faisal Mohamood (Program Manager of Entity Framework) believes in the following prons and cons of using FKs in a model (Ref 1):</p>
<blockquote>
<h3>Benefits of Foreign Keys</h3>
<ol>
<li>Keeps it simple (for the simple cases)  and allows you to deal with relationship like you deal with them in the database</li>
<li>Technically, you can update relationships without having both ends loaded/materialized. This is however in reality not always interesting since you will likely load both ends but this feature is definitely useful.</li>
</ol>
<h3>Disadvantages of Foreign Keys in the Model</h3>
<ol>
<li>It is a part of the impedance mismatch problem.</li>
<li><strong>It doesn’t allow the concepts that you would expect from relationships in objects (easily getting from one end to the other) for instance</strong>.</li>
<li>Having foreign keys as well as object references for relationship navigation presents the problem of two different artifacts representing relationships – this introduces complexity and now you have to make sure that you keep these two in sync.</li>
</ol>
</blockquote>
<p>I think the biggest disadvantage of FKs (stated in number 2) is the conflict with the object model pattern.</p>
<p>However, it seems that Microsoft decided that both sides of this discussion have their valid points. So in Entity Framework .Net 4, Fks are supported and it is up to the software architects to make their decision to just use  independent associations (.Net 3.5 SP1) or add the FKs to the model.</p>
<p>The following code snippets form ADO.Net blog illustrate the implication of using Fks as part of the model (Ref 2). In our model there are two entities <em>Product </em>and <em>Category</em>, with the association one to many where each <em>Product </em>belongs to one <em>Category.</em></p>
<p>First:  Using the independent association between Product and Category.</p>
<pre class="brush: csharp;">
public void Create_new_Product_in_existing_Category_by_reference()
{
    using (var context = new Context())
    {
        //Create a new product and relate to an existing category
        Product p = new Product
        {
            ID = 1,
            Name = &#34;Bovril&#34;,
            Category = context.Categories
                        .Single(c =&#62; c.Name == &#34;Food&#34;)
        };
        // Note: no need to add the product, because relating
        // to an existing category does that automatically.
        // Also notice the use of the Single() query operator
        // this is new to EF in .NET 4.0 too.
        context.SaveChanges();
    }
}
</pre>
<p>Second: Using the Foreign Key.</p>
<pre class="brush: csharp;">
using (var context = new Context())
{
    //Create a product and a relationship to a known category by ID
    Product p = new Product
    {
        ID = 1,
        Name = &#34;Bovril&#34;,
        CategoryID = 13
    };
    //Add the product (and create the relationship by FK value)
    context.Products.AddObject(p);
    context.SaveChanges();
}
</pre>
<p>Further Reading:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ee373856(VS.100).aspx" target="_blank">[MSDN] Defining and Managing Relationships (Entity Framework)</a></li>
<li><a href="http://mosesofegypt.net/post/Inheritance-and-Associations-with-Entity-Framework-Part-3.aspx" target="_blank">Inheritance and Associations with Entity Framework Part 3</a></li>
</ul>
<p>References:</p>
<ol>
<li><a href="http://blogs.msdn.com/efdesign/archive/2008/10/27/foreign-keys-in-the-conceptual-and-object-models.aspx" target="_blank">[blogs.msdn.com/EFDesign]Foreign Keys in the Conceptual and Object Models</a></li>
<li><a href="http://blogs.msdn.com/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx" target="_blank">[blogs.msdn.com/EFDesign]Foreign Keys in the Entity Framework</a></li>
</ol>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[&iquest;Linq to Sql &oacute; Entity Framework?]]></title>
<link>http://calamitatum.wordpress.com/2009/11/08/linq-to-sql-entity-framework/</link>
<pubDate>Sun, 08 Nov 2009 02:55:07 +0000</pubDate>
<dc:creator>Jhonny López Ramírez</dc:creator>
<guid>http://calamitatum.wordpress.com/2009/11/08/linq-to-sql-entity-framework/</guid>
<description><![CDATA[Se me ha preguntado recientemente bajo qué criterios debía tomarse la decisión de usar EF o LINQ2SQL]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p align="justify">Se me ha preguntado recientemente bajo qué criterios debía tomarse la decisión de usar EF o LINQ2SQL y haré aquí un resumen de los que considero debían tenerse en cuenta:</p>
<p align="justify">En primer lugar debo decir que tengo la impresión de que el proyecto Linq to Sql, a pesar de ser una consecuencia esperable en términos de niveles de abstracción, fue desarrollado como un mientras-lanzamos-EF. Eso no hace que haya sido una mala herramienta y, casi que por el contrario, ha opacado en algunos escenarios al mismo EF. Si analizamos un poco el estado del arte del desarrollo web, lenguajes y frameworks ligeros como Ruby on Rails han devenido adicionalmente en ORM’s ligeros y allí tenemos en L2S un claro ejemplo. Así las cosas, L2S está orientado al desarrollo rápido de aplicaciones conectadas a datos en arquitecturas web o de escritorio. Hace sumamente sencillo el acceso a datos en gran parte por la naturaleza misma de Linq y su similitud con el Sql.</p>
<p align="justify">Con Entity Framework sucede que está orientado a la construcción de aplicaciones corporativas en las que el nivel de abstracción del lenguaje de los desarrolladores sea un factor clave. Por ejemplo, permite el mapeo de una clase a diferentes tablas así como usar elementos propios de la programación orientada a objetos tales como la herencia y el polimorfismo. Esto no en todos los casos es una ventaja puesto que tiende a hacer más complejas las situaciones que representa y deriva en olvidar los objetos POCO que tan cómodos suelen resultarnos, aunque sobre esto se haya prometido que en la versión 4.0 del framework se permitirá la compatibilidad entre clases sencillas de un modelo de negocios y EF.</p>
<p align="justify">Dicho lo anterior, yo usaría estas listas de chequeo para determinar si uso el uno o el otro:</p>
<h3 align="justify">¿Cuándo EF?</h3>
<ul>
<li>
<div align="justify"><strong>Cuando se trata de una aplicación que puede estar conectada a fuentes de datos de diferentes proveedores</strong>. Sobre esto EF lleva un poco la ventaja puesto que los proveedores de acceso a datos de terceros tardan menos en aparecer e incluso MS ofrece uno para Oracle. L2S está prácticamente destinado a trabajar con SQL Server.</div>
</li>
<li>
<div align="justify"><strong>Cuando se necesita un lenguaje de abstracción más cercano a la lógica de negocio</strong>. El nivel de abstracción de EF así como su capa de <em>Object Services </em>es mucho más amplia y está orientada a no ser simplemente un ORM sino todo un lenguaje conceptual a la hora de desarrollar aplicaciones conectadas a datos.</div>
</li>
<li>
<div align="justify"><strong>Cuando se estima que la aplicación sea escalable y de largo desarrollo en el tiempo</strong>. La lógica que se puede derivar de aplicaciones sobre EF es mucho más flexible por lo que se puede extender y escalar fácilmente a medida que el proyecto de software crece.</div>
</li>
</ul>
<h3 align="justify">¿Cuándo L2S?</h3>
<ul>
<li>
<div align="justify"><strong>Cuando se desarrolla una aplicación de nivel medio y pequeño</strong>. Resulta muy cómodo cuando se habla de aplicaciones en Asp.net mvc y casi que se asume como el ORM especial para este framework de desarrollo web. Pero prácticamente en cada escenario en el que el desarrollo esté orientado a datos y sea pequeño o mediano L2S, es una excelente solución pues se tiende a escribir menos código que con EF.</div>
</li>
<li>
<div align="justify"><strong>Cuando se trata de una aplicación que tendrá por back-end un único proveedor de bases de datos</strong>. Y ojálá este sea Sql Server. Se han ido desarrollando por terceros proveedores L2S para bases de datos de terceros pero aún se encuentran en fases de desarrollo tempranas.</div>
</li>
<li>
<div align="justify"><strong>Los niveles de abstracción que se usan en la aplicación están casi destinados a coincidir con la persistencia de datos</strong>. Aquí es donde L2S, al ser un ORM en sí, lleva la ventaja sobre EF y donde más podemos notar una solución sencilla a la disparidad entre POO y modelo relacional.</div>
</li>
</ul>
<p align="justify">En conclusión se habrá notado que tiendo a recomendar EF cuando se trata de aplicaciones corporativas, robustas, escalables y de un alto rigor en la representación de la lógica de negocio. Y L2S me parece una herramienta ideal cuando se trata de aplicaciones de tamaño pequeño y hasta mediano. Esto no significa que no se puedan invertir los escenarios de uso, no, pero quizás sí significa que de hacerlo se subutilicen o sean insuficientes los recursos de uno y otro. Para el framework 4.0 se esperan mejoras importantes en ambos y será necesario entonces revisar estas consideraciones. Quizás se vuelva una cuestión de gustos, simplemente.</p>
<p align="justify">Por ahora considero como un excelente término medio Linq to Entities, aunque EF se baste y se sobre por sí mismo.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Using the Entity Framework: Update Operation (Quick Reference)]]></title>
<link>http://jasonstonebraker.wordpress.com/2009/11/02/using-the-entity-framework-update-operation-quick-reference/</link>
<pubDate>Mon, 02 Nov 2009 00:30:36 +0000</pubDate>
<dc:creator>Jason Stonebraker</dc:creator>
<guid>http://jasonstonebraker.wordpress.com/2009/11/02/using-the-entity-framework-update-operation-quick-reference/</guid>
<description><![CDATA[How to Use the Entity Framework to Update Records in a Relational Database This quick reference is f]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h2>How to Use the Entity Framework to Update Records in a Relational Database</h2>
<p>This quick reference is for those who are using the Entity Framework and want examples of how to perform everyday CRUD tasks. We&#8217;ll take a look at how to update objects and associated objects using the Entity Framework.</p>
<h3>Quick Reference Setup</h3>
<p><a href="http://jasonstonebraker.wordpress.com/2009/10/24/linq-to-entities-movies-example-setup/">Entity Framework &#38; Linq to Entities: “Movies” Example Setup</a> contains diagrams representing the database structure, entity data model, and entity object model used in the following code examples.</p>
<h3>Update a Director object using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = _entities.DirectorSet.
               Where(d =&#62; d.Name == "Spike Jonze").First();

     spikeJonze.Name = "Adam Spiegel a.k.a \"Spike Jonze\"";
     _entities.SaveChanges();

     Console.ReadLine();
}</pre>
<p style="padding-top:0;">First, we retrieve a Director object by specifying a value for the Name property in a lambda expression. Next, we update the Director&#8217;s Name property. Finally, we call the ObjectContext&#8217;s SaveChanges method to commit the changes to the model and the database.</p>
<h3>Using the ObjectStateManager when Updating a Director object using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = _entities.DirectorSet.
               Where(d =&#62; d.Name == "Spike Jonze").First();

     spikeJonze.Name = "Adam Spiegel a.k.a \"Spike Jonze\"";

     ObjectStateEntry entry = _entities.ObjectStateManager.
               GetObjectStateEntry(spikeJonze.EntityKey);
     IEnumerable&#60;string$gt; modProps = entry.
               GetModifiedProperties();

     foreach (string prop in modProps)
     {
          Console.WriteLine("Modified Property: {0}",
                    prop.ToString());

          Console.WriteLine("IsDbNull: {0}",
                    entry.OriginalValues.
                    IsDBNull(
                         entry.OriginalValues.GetOrdinal(prop)
                    )
          );

          Console.WriteLine("Changed from: {0}",
                    entry.OriginalValues[prop]);

          Console.WriteLine("Changed to: {0}",
                    entry.CurrentValues[prop]);
     }

     Console.WriteLine(&#34;Entity State: {0}&#34;, entry.State);

     Console.WriteLine("\n--&#62; All Original Values");
     for (int i = 0; i &#60; entry.OriginalValues.FieldCount; i++)
     {
          Console.WriteLine(&#34;{0}: {1}&#34;,
                    entry.OriginalValues.GetName(i),
                    entry.OriginalValues[i]);
     }

     _entities.SaveChanges();

     Console.ReadLine();
}</pre>
<p style="padding-top:0;">After modifying a property an object, we can use the ObjectStateManager to access state information such as, which properties were modified, those properties original values, their current values, and other helpful information.</p>
<p>To access this information we call the ObjectContext&#8217;s GetObjectStateEntry method passing in the Director&#8217;s EntityKey. This method returns the ObjectStateEntry for the specified Director object. To determine which properties have been modified, we call the ObjectStateEntries GetModifiedProperties method which returns a collection of the names of any properties whose current values are different from their original values.</p>
<p>To determine the original value of a property, we retrieve the value at a given index in the ObjectStateEntry&#8217;s OriginalValues collection. Since OriginalValues is an indexed collection we can specify either the number of the database column or the name of the column (or property) as such, <code>entry.OriginalValues["name"]</code>. We then use the CurrentValues collection to retrieve the current value of the modified property.</p>
<p>Lastly, for the purpose of illustration, we loop over the OriginalValues collection and output all of the Director object&#8217;s property names and their respective values.</p>
<p><strong>Here is the output:</strong></p>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">Modified Property: Name
IsDbNull: False
Changed from: Spike Jonze
Changed to: Adam Spiegel a.k.a "Spike Jonze"
Entity State: Modified

--&#62; All Original Values
ID: 33
Name: Spike Jonze
Hometown: Rockville Maryland
Birthday: 10/22/1969
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Using the Entity Framework: Delete Operation (Quick Reference)]]></title>
<link>http://jasonstonebraker.wordpress.com/2009/11/01/using-the-entity-framework-delete-operation-quick-reference/</link>
<pubDate>Sun, 01 Nov 2009 19:01:57 +0000</pubDate>
<dc:creator>Jason Stonebraker</dc:creator>
<guid>http://jasonstonebraker.wordpress.com/2009/11/01/using-the-entity-framework-delete-operation-quick-reference/</guid>
<description><![CDATA[How to Use the Entity Framework to Delete Records in a Relational Database This quick reference is f]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h2>How to Use the Entity Framework to Delete Records in a Relational Database</h2>
<p>This quick reference is for those who are trying out the Entity Framework and want examples of how to perform everyday CRUD tasks. We&#8217;ll take a look at how to delete objects and associated objects using the Entity Framework.</p>
<h3>Quick Reference Setup</h3>
<p><a href="http://jasonstonebraker.wordpress.com/2009/10/24/linq-to-entities-movies-example-setup/">Entity Framework &#38; Linq to Entities: “Movies” Example Setup</a> contains diagrams representing the database structure, entity data model, and entity object model used in the following code examples.</p>
<h3>Delete a Movie object using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Movie movieToDelete =
          (from m in _entities.MovieSet
           where m.Title == "The Princess Bride"
	   select m).First();

     _entities.DeleteObject(movieToDelete);
     Console.WriteLine("--&#62; {0}: Marked as Deleted in Model",
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}",
          movieToDelete.EntityState); // Deleted

     _entities.SaveChanges();
     Console.WriteLine("\n--&#62; {0}:
          Deleted from Model and Datasource",
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}",
          movieToDelete.EntityState); // Detached
     Console.ReadLine();
}</pre>
<p style="padding-top:0;">First we retrieve the Movie we wish to delete. To do so we make use of the First extension method on the Linq query. The First method returns a single object rather than a collection. We then call the ObjectContext&#8217;s DeleteObject method passing it the Movie object we retrieved. At this point the ObjectStateManager has marked the object as having a &#8220;Deleted&#8221; state, though the Movie object has not been deleted from the model or the database. Calling the ObjectContext&#8217;s SaveChanges method detaches the Movie from the model and deletes the corresponding record from the database.</p>
<p><strong>Here is the output:</strong></p>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">--&#62; The Princess Bride: Marked as Deleted in Model
Entity State: Deleted

--&#62; The Princess Bride: Deleted from Model and Datasource
Entity State: Detached
</pre>
<h3>Delete a Director object and its associated Movie objects using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = _entities.DirectorSet.
               Where(d =&#62; d.Name == "Spike Jonze").First();

     // Remember to Load associated objects
     spikeJonze.Movies.Load(); 

     Console.WriteLine("Number of Movies to Delete: {0}",
               spikesMovies.Count());

     // Using ToList is also important
     foreach (var movie in spikeJonze.Movies.ToList())
     {
          _entities.DeleteObject(movie);
          Console.WriteLine("--&#62; Movie {0}:
                    Marked for Deletion", movie.Title);
     }

     _entities.DeleteObject(spikeJonze);
     Console.WriteLine("--&#62; Director {0}:
               Marked for Deletion", spikeJonze.Name);

     _entities.SaveChanges();
     Console.WriteLine("--&#62; Director and
               associated Movies Deleted");

     Console.ReadLine();
}</pre>
<p style="padding-top:0;">We retrieve the Director by passing a lambda expression to the Where extension method and use the First method to specify that we only want the first Movie object in the resulting collection. We then call the Load method on the Director&#8217;s Movies collection. This populates any Movies associated with the Director with values retrieved from the database. Each populated Movie object is added to the Movies collection. Neglecting to Load the Movies collection would result in an exception being thrown during the call to SaveChanges. This is because the Movies collection would appear to the ObjectContext to be empty, therefore, none of the Movies would be deleted. However, when SaveChanges is called, it would be determined that the Director does indeed have associated Movies in the database, and could therefore, not be deleted. Using the technique described in this example requires that objects must be loaded in order to be deleted.</p>
<p>Now that we have the Movies associated with the Director, we can loop over the collection and delete each Movie. Notice that the ToList extension method is called on the Director&#8217;s Movies collection. Doing so ensures that we are working with a separate instance of the Movies collection. If we tried to perform a delete operation on items in the actual collection we were iterating through, we would receive an error.</p>
<p>Once the Director&#8217;s Movies have been marked for deletion, we mark the Director for deletion as well. The subsequent call to the ObjectContext&#8217;s SaveChanges method results in the Director and his associated Movies being detached from the ObjectContext and deleted from the database.</p>
<p><strong>Here is the output:</strong></p>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">--&#62; Number of Movies to Delete: 4

--&#62; Movie Adaptation: Marked for Deletion
--&#62; Movie Where the Wild Things Are: Marked for Deletion
--&#62; Movie Human Nature: Marked for Deletion
--&#62; Movie Being John Malkovich: Marked for Deletion

--&#62; Director Spike Jonze: Marked for Deletion

--&#62; Director and Associated Movies Deleted
</pre>
<h3>Delete a Movie object without loading it using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     int movieID = 105;
     int directorID = 2;

     Movie princessBride = new Movie();
     princessBride.ID = movieID;
     princessBride.DirectorReference.EntityKey =
               new EntityKey("MovieEntities.DirectorSet",
                         "ID", directorID);

     _entities.AttachTo("MovieEntities.MovieSet",
               princessBride);
     _entities.DeleteObject(princessBride);
     _entities.SaveChanges();

     Console.ReadLine();
}</pre>
<p style="padding-top:0;">Assuming we know the ID of a Movie object, we can delete it without having to load it into the ObjectContext. We do so by creating a new Movie object, setting its ID property to the known value, and creating the EntityKeys for any EntityReferences the object may have. We then pass the Movie object to the ObjectContext&#8217;s AttachTo method, delete the object, and save the changes.</p>
<p>Unfortunately, I&#8217;ve not yet discovered a way to delete objects based on a property value, such as Movie.DirectorID, without loading the objects into the ObjectContext or performing a Linq query, both of which would require a call to the database. If you are aware of a method for doing so, please leave a comment and let us all know.</p>
<h3>Exploring EntityStates when Deleting a Movie object using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Movie movieToDelete =
          (from m in _entities.MovieSet
           where m.Title == "The Princess Bride"
	   select m).First();

     // Movie retrieved
     Console.WriteLine("--&#62; {0}: Movie Retrieved",
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}",
          movieToDelete.EntityState); // Deleted

     EntityKey movieToDeleteKey = _entities.
          CreateEntityKey("MovieEntities.MovieSet",
                                   movieToDelete);
     Console.WriteLine("Movie's EntityKey Value: {0}",
          movieToDeleteKey.EntityKeyValues[0].Value);
     Console.WriteLine("DirectorReference
          EntityKey is null: {0}",
          movieToDelete.DirectorReference.EntityKey == null);
     Object deletedMovie = null;
     bool movieToDeleteExists = _entities.
          TryGetObjectByKey(movieToDeleteKey,
               out deletedMovie);
     Console.WriteLine("Movie to Delete Exists
          in ObjectContext: {0}",
          movieToDeleteExists);

     // Movie marked for deletion
     _entities.DeleteObject(movieToDelete);
     Console.WriteLine("\n\n--&#62; {0}: Marked as Deleted in Model",
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}",
          movieToDelete.EntityState); // Deleted

     movieToDeleteKey = _entities.
          CreateEntityKey("MovieEntities.MovieSet",
               movieToDelete);
     Console.WriteLine("Movie's EntityKey Value: {0}",
          movieToDeleteKey.EntityKeyValues[0].Value);
     Console.WriteLine("DirectorReference
          EntityKey is null: {0}",
          movieToDelete.DirectorReference.EntityKey == null);
     deletedMovie = null;
     movieToDeleteExists = _entities.
          TryGetObjectByKey(movieToDeleteKey,
               out deletedMovie);
     Console.WriteLine("Movie to Delete Exists
          in ObjectConext: {0}",
          movieToDeleteExists);

     // Movie detached from model and deleted from database
     _entities.SaveChanges();
     Console.WriteLine("\n\n--&#62; {0}:
          Deleted from Model and Datasource",
          movieToDelete.Title);
     Console.WriteLine("Entity State: {0}",
          movieToDelete.EntityState); // Detached

     movieToDeleteKey = _entities.
          CreateEntityKey("MovieEntities.MovieSet",
               movieToDelete);
     Console.WriteLine("Movie's EntityKey Value: {0}",
          movieToDeleteKey.EntityKeyValues[0].Value);
     Console.WriteLine("DirectorReference
          EntityKey is null: {0}",
          movieToDelete.DirectorReference.EntityKey == null);
     deletedMovie = null;
     movieToDeleteExists = _entities.
          TryGetObjectByKey(movieToDeleteKey,
               out deletedMovie);
     Console.WriteLine("Movie to Delete Exists
          in ObjectContext: {0}",
          movieToDeleteExists);

     Console.ReadLine();
}</pre>
<p style="padding-top:0;">After marking the Movie for deletion, we are still able to make use of the object. In this case we grab the Movies EntityKey and make a call to the ObjectContext&#8217;s TryGetObjectByKey method. This method returns <code>true</code> if a Movie with the specified EntityKey exists in the model. It also creates a reference to the Movie and places it in the <code>out</code> parameter <code>deletedMovie</code>.</p>
<p>Calling the ObjectContext&#8217;s SaveChanges method detaches the Movie object from the model. The object retains its data values including its EntityKey, however, any relationships it might have had (such as the relationship used for the DirectorReference in this case) are lost. We are still able to retrieve the EntityKey from the detached object, however, the subsequent call to TryGetObjectByKey returns <code>false</code> because the Movie is no longer part of the ObjectContext.</p>
<p><strong>Here is the output:</strong></p>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">--&#62; The Princess Bride: Movie Retrieved
Entity State: Unchanged
Movie's EntityKey Value: 97
DirectorReference EntityKey is null: False
Movie to Delete Exists in ObjectContext: True

--&#62; The Princess Bride: Marked as Deleted in Model
Entity State: Deleted
Movie's EntityKey Value: 97
DirectorReference EntityKey is null: True
Movie to Delete Exists in ObjectContext: True

--&#62; The Princess Bride: Deleted from Model and Datasource
Entity State: Detached
Movie's EntityKey Value: 97
DirectorReference EntityKey is null: True
Movie to Delete Exists in ObjectContext: False
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Using the Entity Framework: Create Operation (Quick Reference)]]></title>
<link>http://jasonstonebraker.wordpress.com/2009/10/31/using-the-entity-framework-create-operation-quick-reference/</link>
<pubDate>Sat, 31 Oct 2009 02:32:23 +0000</pubDate>
<dc:creator>Jason Stonebraker</dc:creator>
<guid>http://jasonstonebraker.wordpress.com/2009/10/31/using-the-entity-framework-create-operation-quick-reference/</guid>
<description><![CDATA[How to Use the Entity Framework to Create Records in a Relational Database This quick reference is f]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h2>How to Use the Entity Framework to Create Records in a Relational Database</h2>
<p>This quick reference is for those who are trying out the Entity Framework and want examples of how to perform everyday CRUD tasks. We&#8217;ll take a look at how to create objects and manage relationships working with the Entity Framework&#8217;s occasionally unclear object model. </p>
<h3>Quick Reference Setup</h3>
<p><a href="http://jasonstonebraker.wordpress.com/2009/10/24/linq-to-entities-movies-example-setup/">Entity Framework &#38; Linq to Entities: “Movies” Example Setup</a> contains diagrams representing the database structure, entity data model, and entity object model used in the following code examples.</p>
<h3>Create a Director object using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = Director.CreateDirector(
          0,
          "Spike Jonze",
          "Rockville Maryland",
          "10/22/1969"
     );

     // Use the AddToDirectorSet method
     _entities.AddToDirectorSet(spikeJonze);

     // Could have also used the AddObject method
     // _entities.AddObject("MovieEntities.DirectorSet",
     //     spikeJonze);

     Console.WriteLine("--&#62; Director added to DirectorSet");
     Console.WriteLine("EntityKey is temporary: {0}",
          spikeJonze.EntityKey.IsTemporary);

     _entities.SaveChanges();

     Console.WriteLine("--&#62; Changes Saved");
     Console.WriteLine("EntityKey is temporary: {0}",
          spikeJonze.EntityKey.IsTemporary);
     Console.WriteLine("EntityKey Key: {0},
          EntityKey Value: {1}",
          spikeJonze.EntityKey.EntityKeyValues[0].Key,
          spikeJonze.EntityKey.EntityKeyValues[0].Value);

     Console.ReadLine();
}</pre>
<p style="padding-top:0;">We use the CreateDirector to initialize a new Director object. Notice that 0 is specified for the ID parameter. Though this argument is required, the value you provide is of no consequence. Once the Director is added to the DirectorSet, a temporary EntityKey is created. The call to SaveChanges adds the Director object&#8217;s data values to the database and the primary key resulting from the database insert is retrieved. From that point on the EntityKey&#8217;s value will be synchronized with the identity column for the Director record in the database.</p>
<p>There are multiple ways to add an entity object to the ObjectContext. Two of which are illustrated in this example. Which method you choose is a matter of preference.</p>
<p><strong>Here is the output:</strong></p>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">
--&#62; Director added to DirectorSet
EntityKey is temporary: True
--&#62; Changes Saved
EntityKey is temporary: False
EntityKey Key: ID, EntityKey Value: 27
</pre>
<h3>Create a Director object and an associated Movie object using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director spikeJonze = new Director {
          Name = "Adam Spiegel a.k.a., Spike Jonze",
          Hometown = "Rockville Maryland",
          Birthday = "10/22/1969"
     };
     _entities.AddToDirectorSet(spikeJonze);

     Movie wildThings = new Movie {
          Title = "Where the Wild Things Are",
          DateReleased = DateTime.Parse("10/1/2009")
     };
     spikeJonze.Movies.Add(wildThings);

     _entities.SaveChanges();
     Console.ReadLine();
}</pre>
<p style="padding-top:0;">We use object initialization syntax to create a Director object and then add it to the ObjectContext&#8217;s DirectorSet collection. We then create a Movie object and add it to the Director&#8217;s Movies collection. Doing so creates a relationship (with corresponding temporary EntityKeys) between the Director and the Movie. Calling the SaveChanges method updates the database to reflect the changes we&#8217;ve made to the entity data model.</p>
<p style="padding-top:5px;">There are multiple ways to initialize object in CSharp. When working with the Entity Framework, I prefer to use object initialization syntax (used in this example) in lieu of using the CreateDirector factory method. Though there is a benefit to using the factory method in that you are forced to provide initial values for all properties. What you use is a matter of preference.</p>
<h3>Create a Movie object and associate it with an existing Director object using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director robReiner = _entities.DirectorSet.Where(
               d =&#62; d.Name == "Rob Reiner").First();

     Movie thePrincessBride = new Movie {
          Title = "The Princess Bride",
          DateReleased = DateTime.Parse("1/1/1987")
     };

     robReiner.Movies.Add(thePrincessBride);
     _entities.SaveChanges();
     Console.ReadLine();
}</pre>
<p style="padding-top:0;">First we load the appropriate Director object. Next we create the Movie object and add it to the Director&#8217;s Movies collection. Doing so creates the necessary relationship. Finally, we call the ObjectContext&#8217;s SaveChanges() method which inspects the context&#8217;s ObjectStateManager and commits any changes that had been made to the model&#8217;s entities or associations since it was created or since SaveChanges() was last called.</p>
<h3>Create a Movie object and associate it with an existing Director object without loading the Director object using the Entity Framework</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     int robReinerID = 2;
     Movie thePrincessBride = new Movie {
          Title = "The Princess Bride (New)",
          DateReleased = DateTime.Parse("1/1/1987")
     };

     thePrincessBride.DirectorReference.EntityKey = new
          EntityKey("MovieEntities.DirectorSet",
                    "ID", robReinerID);
     _entities.AddToMovieSet(thePrincessBride);
     _entities.SaveChanges();
     Console.ReadLine();
}</pre>
<p style="padding-top:0;">Since we know the Director&#8217;s ID, there is no need to load the Director object in order to create the Movie. It is necessary, however, to set the EntityKey property of the DirectorReference (an EntityReference type). Note that the first argument passed to the EntityKey&#8217;s constructor is an EntitySet within the ObjectContext; e.g., MovieEntities.DirectorSet.</p>
<h3>Exploring the Entity Framework&#8217;s ObjectStateManager</h3>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">private static MovieEntities _entities = new MovieEntities();

static void Main(string[] args)
{
     Director robReiner = _entities.DirectorSet.Where(
               d =&#62; d.Name == "Rob Reiner").First();

     Movie thePrincessBride = new Movie {
          Title = "The Princess Bride",
          DateReleased = DateTime.Parse("1/1/1987")
     };

     robReiner.Movies.Add(thePrincessBride);
     IEnumerable&#60;ObjectStateEntry&#62; entries =
          _entities.ObjectStateManager.
          GetObjectStateEntries(EntityState.Added);

     foreach (ObjectStateEntry entry in entries)
     {
          Console.WriteLine("Entity Set: {0}", entry.EntitySet);
	  Console.WriteLine("IsRelationship: {0}",
               entry.IsRelationship);
	  Console.WriteLine("State: {0}", entry.State);

	  if (!entry.IsRelationship)
	  {
	     Console.WriteLine("EntityKey is null: {0}",
                  entry.EntityKey.EntityKeyValues == null);
             Console.WriteLine("EntityKey is temporary: {0}",
                  entry.EntityKey.IsTemporary);
	  }

          entry.AcceptChanges();
          Console.WriteLine("--&#62; Changes Accepted");

	  if (!entry.IsRelationship)
	  {
	        Console.WriteLine("EntityKey is: {0}",
                     entry.EntityKey.EntityKeyValues.First());
		Console.WriteLine("EntityKey is temporary: {0}",
                     entry.EntityKey.IsTemporary);
	  }

          Console.WriteLine("State: {0}\n\n", entry.State);
     }

     // The following call to SaveChanges() does nothing
     // because calling AcceptChanges() on each entry updated
     // their respective states from "Added" to "Unchanged".
     _entities.SaveChanges(); 

     Console.ReadLine();
}</pre>
<p style="padding-top:0;">First we add a Movie to a Director&#8217;s collection of Movies. Doing so adds two ObjectStateEntries to the ObjectStateManager. ObjectStateEntries are used to track changes made to the entity model. One of the entries is for the Movie entity that was added and the second is for the relationship that was created between the Movie and the Director. We then grab the ObjectStateEntries where the EntityState equals &#8220;Added&#8221;. Looping over the ObjectStateEntries allows us to see various properties of the entries before and after AcceptChanges is called. When AcceptChanges is called on a given entry, its state is set to &#8220;Unchanged&#8221;. Therefore, the subsequent call to SaveChanges does nothing since the state of all ObjectStateEntries is &#8220;Unchanged&#8221; at the time SaveChanges is called. Retrieving a list of Movies would reveal that the Movie was <em>not</em> inserted into the database.</p>
<p><strong>Here is the output:</strong></p>
<pre style="background-color:#f5f5f5;border:1px solid #cccccc;overflow:auto;padding:10px;">
Entity Set: FK_Movies_Directors
IsRelationship: True
State: Added
--&#62; Changes Accepted
State: Unchanged

Entity Set: MovieSet
IsRelationship: False
State: Added
EntityKey is null: True
EntityKey is temporary: True
--&#62; Changes Accepted
EntityKey is: [ID, 0]
EntityKey is temporary: False
State: Unchanged
</pre>
</div>]]></content:encoded>
</item>

</channel>
</rss>
