<?xml version="1.0" encoding="UTF-8"?>
<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/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>A Programmer with Microsoft tools &#187; Entity Framework</title>
	<atom:link href="http://msprogrammer.serviciipeweb.ro/category/howto/entity-framework-howto/feed/" rel="self" type="application/rss+xml" />
	<link>http://msprogrammer.serviciipeweb.ro</link>
	<description>A programmer journey through code, books and tools</description>
	<lastBuildDate>Mon, 14 May 2012 06:59:14 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Generating history trigger with EF , edmx and TT files</title>
		<link>http://msprogrammer.serviciipeweb.ro/2010/09/27/generating-history-trigger-with-ef-edmx-and-tt-files/</link>
		<comments>http://msprogrammer.serviciipeweb.ro/2010/09/27/generating-history-trigger-with-ef-edmx-and-tt-files/#comments</comments>
		<pubDate>Mon, 27 Sep 2010 04:38:49 +0000</pubDate>
		<dc:creator>Andrei Ignat</dc:creator>
				<category><![CDATA[.tt]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[EF]]></category>

		<guid isPermaLink="false">http://msprogrammer.serviciipeweb.ro/?p=440</guid>
		<description><![CDATA[I have wrote in an older post ( http://msprogrammer.serviciipeweb.ro/2010/06/28/ef-automatic-history-of-table-and-t4-files-tt-files/ ) how to generate history code for tables . The easy solution was to create a tt file that track for the ObjectContext the SaveChanges for each table that has a “history” in name. the limitation is that , when you raise an sql command such [...]]]></description>
			<content:encoded><![CDATA[<p>I have wrote in an older post ( <a title="http://msprogrammer.serviciipeweb.ro/2010/06/28/ef-automatic-history-of-table-and-t4-files-tt-files/" href="http://msprogrammer.serviciipeweb.ro/2010/06/28/ef-automatic-history-of-table-and-t4-files-tt-files/">http://msprogrammer.serviciipeweb.ro/2010/06/28/ef-automatic-history-of-table-and-t4-files-tt-files/</a> ) how to generate history code for tables . The easy solution was to create a tt file that track for the ObjectContext the SaveChanges for each table that has a “history” in name. the limitation is that , when you raise an sql command such as &#8220;update table &#8221; you must load from database a lot of rows for this&#8230;.</p>
<p>Now I want to show the same thing, but generating triggers in database for that ! I start also from edmx file and with a template stealed from <a title="http://forums.asp.net/p/1599616/4083198.aspx" href="http://forums.asp.net/p/1599616/4083198.aspx">http://forums.asp.net/p/1599616/4083198.aspx</a> ( to have type of fields in the database ) and another stealed and modified from StackOverflow(to generate trigger for after insert , update, delete) I manage to have a solution to generate sql tables and trigger code.</p>
<p>When is that good ?At the beginning stages of a project when the table structure changes by adding a new parameter.</p>
<p>Sample code generated for table Notes(ID, TextNote, PersonID)</p>
<pre class="brush: sql;">
print 'Create table Notes_History ';
Create Table Notes_History(
		ID_Notes_History BIGINT IDENTITY NOT NULL
		,History_Action varchar(50)
		,History_From varchar(100) default HOST_NAME()
		,History_User varchar(50) default SYSTEM_USER
		,History_Date varchar(50) default  getdate()
	   ,Id  int   NOT NULL
	   ,Textnote  nvarchar (255)  NULL
	   ,PersonId  int   NULL
	)
print 'end Create table Notes_History ';
GO
print 'create trigger for Notes'
GO
CREATE TRIGGER dbo.TR_IUP_Notes
   ON  Notes
   AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    SET NOCOUNT ON;
	DECLARE @Ins int

DECLARE @Del int

SELECT @Ins = Count(*) FROM inserted

SELECT @Del = Count(*) FROM deleted
if(@Ins  + @Del = 0)
	return;

declare @operation varchar(50)
	set @operation ='update';
	if(@ins &lt; @del)
		set @operation ='delete';
	if(@ins &gt; @del)
		set @operation ='insert';

	if(@ins &lt;= @del)
	begin
		INSERT INTO Notes_History(History_Action ,Id,Textnote,PersonId)
			select @operation ,Id,Textnote,PersonId from deleted
	end
    else
	begin
    INSERT INTO Notes_History(History_Action ,Id,Textnote,PersonId)
			select @operation ,Id,Textnote,PersonId from inserted
	end
END
</pre>
<p>The drawback of the code : the user that executes is not always the logged sql server user&#8230;<br />
Anyway, what  you have to do to use this automatically generated history/audit for tables ?</p>
<p>download <a href="http://msprogrammer.serviciipeweb.ro/wp-content/uploads/2010/09/historysql.zip">historysql</a> and modify</p>
<p>string inputFile = @&#8221;Model1.edmx&#8221;;</p>
<p>from historysql.tt to your edmx name. Then take the generated code and execute in sql server.</p>
]]></content:encoded>
			<wfw:commentRss>http://msprogrammer.serviciipeweb.ro/2010/09/27/generating-history-trigger-with-ef-edmx-and-tt-files/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Asp.NET MVC and DOS &#8211; re-using the ViewModels</title>
		<link>http://msprogrammer.serviciipeweb.ro/2010/07/05/asp-net-mvc-and-dos-re-using-the-viewmodels/</link>
		<comments>http://msprogrammer.serviciipeweb.ro/2010/07/05/asp-net-mvc-and-dos-re-using-the-viewmodels/#comments</comments>
		<pubDate>Mon, 05 Jul 2010 04:17:04 +0000</pubDate>
		<dc:creator>Andrei Ignat</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[DOS]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[console]]></category>
		<category><![CDATA[ViewModel]]></category>

		<guid isPermaLink="false">http://msprogrammer.serviciipeweb.ro/?p=326</guid>
		<description><![CDATA[(Please read first : http://msprogrammer.serviciipeweb.ro/2010/03/29/asp-net-mvc-orm-and-viewmodels/ )
One of the biggest challenges in programming was write once- GUI everywhere ( Ok, ORM impedance mismatch is another story)
I mean by that re-using the logic from an application in another application. ASP.NET MVC , with the commitment to strongly viewmodels, make me think that it will be now easier [...]]]></description>
			<content:encoded><![CDATA[<p>(Please read first : <a href="http://msprogrammer.serviciipeweb.ro/2010/03/29/asp-net-mvc-orm-and-viewmodels/" target="_blank">http://msprogrammer.serviciipeweb.ro/2010/03/29/asp-net-mvc-orm-and-viewmodels/</a> )</p>
<p>One of the biggest challenges in programming was write once- GUI everywhere ( Ok, ORM impedance mismatch is another story)</p>
<p>I mean by that re-using the logic from an application in another application. ASP.NET MVC , with the commitment to strongly viewmodels, make me think that it will be now easier to transfer the viewmodels to an console application.</p>
<p>Let&#8217;s see the usual Employee-Department and creation.</p>
<p>First the Database :</p>
<p><img src="http://msprogrammer.serviciipeweb.ro/wp-content/uploads/ASP.NETMVCORMandViewModels_135E/image.png" alt="" /></p>
<p>Then the ViewModel for creating an employeeand for list of employees</p>
<pre class="brush: csharp;">

public class ViewModelEmployee
 {
 public static DepartmentList ListOfDepartments
 {
 get
 {
 //TODO : put this into cache to not load every time
 DepartmentList dl = new DepartmentList();
 dl.Load();
 return dl;
 }
 }
 }
 public class ViewModelEmployeeCreate : ViewModelEmployee
 {
 public Employee emp = new Employee();

 public static void SaveNew(Employee emp)
 {
 emp.SaveNew();
 }
 }
 public class ViewModelEmployeeList : ViewModelEmployee
 {
 public EmployeeList employees;
 public void Load()
 {
 employees = new EmployeeList();
 employees.Load();
 }
 }
</pre>
<p>And now the magic :</p>
<table width="100%">
<tbody>
<tr>
<td>ASP.NET MVC</td>
<td>DOS</td>
</tr>
<tr>
<td valign="top">
<pre class="brush: csharp;">

[HttpPost]
 public ActionResult Create(Employee emp,long DepartmentID)
 {
 try
 {

 emp.Department = new Department() { ID = DepartmentID };
 ViewModelEmployeeCreate.SaveNew(emp);

 return RedirectToAction(&quot;Index&quot;);
 }
 catch(Exception ex)
 {
 ModelState.AddModelError(&quot;&quot;, ex.Message);
 return View(new ViewModelEmployeeCreate(){emp=emp});
 }
 }
</pre>
</td>
<td valign="top">
<pre class="brush: csharp;">

Console.WriteLine(&quot;choose department&quot;);
 var listdep=ViewModelEmployee.ListOfDepartments;
 foreach (var item in listdep)
 {
 Console.WriteLine(item.ID + &quot;)&quot; + item.Name);

 }
 string s=Console.ReadLine();
 long DepartmentID;
 if (!long.TryParse(s, out DepartmentID))
 {
 Console.WriteLine(&quot;exit : not a long :&quot; + s);
 return;
 }
 if (!listdep.Exists(item =&gt; item.ID == DepartmentID))
 {
 Console.WriteLine(&quot;not a valid id:&quot; + s);
 return;
 }
 Employee emp = new Employee();
 emp.Department = new Department() { ID = DepartmentID };
 Console.Write(&quot;employee name ?&quot;);
 emp.Name= Console.ReadLine();
 ViewModelEmployeeCreate.SaveNew(emp);
</pre>
</td>
</tr>
</tbody>
</table>
<p>Now for listing employees:</p>
<table width="100%">
<tbody>
<tr>
<td>ASP.NET MVC</td>
<td>DOS</td>
</tr>
<tr>
<td valign="top">
<pre class="brush: csharp;">
public ActionResult Index()
        {
            ViewModelEmployeeList vmel = new ViewModelEmployeeList();
            vmel.Load();
            return View(vmel);
        }
</pre>
</td>
<td valign="top">
<pre class="brush: csharp;">
  ViewModelEmployeeList vmel = new ViewModelEmployeeList();
            vmel.Load();
            foreach (var item in vmel.employees)
            {
                Console.WriteLine(item.Name);
            }
</pre>
</td>
</tr>
</tbody>
</table>
<p>As you can see , the codes are really similar ( although the console application is filled with first verification and the MVC is not )</p>
<p>Please download the application from <a href="http://msprogrammer.serviciipeweb.ro/wp-content/uploads/2010/07/testaddropdownlist.zip">testaddropdownlist</a></p>
<p>To install : run the emp.sql file, change in the app.config/web.config the connection string to point to the real database/sql server.</p>
<p>Summary : This simple application shows how to re-use ViewModels from an ASP.NET MVC and a DOS Console Application</p>
<p>Homework : Add  WindowsForms application and do the same.</p>
]]></content:encoded>
			<wfw:commentRss>http://msprogrammer.serviciipeweb.ro/2010/07/05/asp-net-mvc-and-dos-re-using-the-viewmodels/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>EF , automatic history of table and T4 files (TT files)</title>
		<link>http://msprogrammer.serviciipeweb.ro/2010/06/28/ef-automatic-history-of-table-and-t4-files-tt-files/</link>
		<comments>http://msprogrammer.serviciipeweb.ro/2010/06/28/ef-automatic-history-of-table-and-t4-files-tt-files/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 04:51:55 +0000</pubDate>
		<dc:creator>Andrei Ignat</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[automatic history]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[EF]]></category>
		<category><![CDATA[Entity framework]]></category>

		<guid isPermaLink="false">http://msprogrammer.serviciipeweb.ro/?p=275</guid>
		<description><![CDATA[Usually the data of the tables should be tracking for who modified it.
Think about inserting/updating/deleting an employee :   you must know who did those actions and when. So you create another table, identically as structure, and you add another 3 fields , such as [ModifiedDate](when), [ModifiedBy](who), [ModifiedType] (what : insert, update, delete).
There are several methods [...]]]></description>
			<content:encoded><![CDATA[<p>Usually the data of the tables should be tracking for who modified it.</p>
<p>Think about inserting/updating/deleting an employee :   you must know who did those actions and when. So you create another table, identically as structure, and you add another 3 fields , such as [ModifiedDate](when), [ModifiedBy](who), [ModifiedType] (what : insert, update, delete).</p>
<p>There are several methods to do it :</p>
<ol>
<li>from database :
<ul>
<li> you can use triggers and insert data into new table</li>
<li>in Sql 2008 , you can use  <a onmousedown="return rwt(this,'','','','3','AFQjCNG2uN5isVcicwAkxWGBHGhOCX7zbw','PmDDPXhR1KFSvnfq0JV2OA','0CCUQFjAC')" href="http://msdn.microsoft.com/en-us/library/bb522489.aspx"><em><em>Change Data Capture </em></em></a>( see also <a title="gui for cdc" href="http://cdchelper.codeplex.com/" target="_blank">http://cdchelper.codeplex.com/</a> for a GUI )</li>
</ul>
</li>
<li>from programming code  &#8211; every time you modify an object, you remember to modify the history object with appropiate data.</li>
</ol>
<p>The drawback with the database approach is that you can not retrieve who done the modifications ( usually the applications connect under a single account and have a roles table)</p>
<p>The drawback with the programming approach is that the programmer must REMEMBER doing so&#8230;If he does not(and does not wrote tests for history), you are stuck&#8230;</p>
<p>In the following I propose an automatically history &#8211; that maps convention over configuration in my template, but it is easy for you to modify.</p>
<p>The solution works with Entity Framework 4.0 and, for more easily spearation of concerns , with POCO generators.</p>
<p>Let&#8217;s say you have the following tables :</p>
<p><a href="http://msprogrammer.serviciipeweb.ro/wp-content/uploads/2010/06/history.png"><img class="alignnone size-full wp-image-307" title="history" src="http://msprogrammer.serviciipeweb.ro/wp-content/uploads/2010/06/history.png" alt="database diagram" width="623" height="449" /></a></p>
<p>As you see we have a Employee and a employee_history, an Department and Department_history</p>
<p>The conventions are:</p>
<p>the history table name = &#8220;object&#8221; table name  +  &#8220;_history&#8221; suffix</p>
<p>the history table fields = &#8220;object&#8221; table name  fields +[ModifiedDate], [ModifiedBy], [ModifiedType]</p>
<p>(if you change those conventions , please change the modelhistory.tt file)</p>
<p>If you want to see in action , please  download code <a href="http://msprogrammer.serviciipeweb.ro/wp-content/uploads/2010/06/history.zip">history</a> and do the following<br />
1. create database tests<br />
2. run history.sql<br />
3. run project<br />
4. if necessay, re-create the model1.edmx with the same name and replace the console application app.config with the new connection string</p>
<p>After works, please add any fields to department table  and to department_history table(same field names/type) .  Re-compile the application and modify the new field in department. You will see the modifications in the department_history table.</p>
<p>Ok,now how we do the magic :</p>
<p>We create two new tt file that points to the model.edmx .</p>
<p>The first one ModelHistory.tt , takes care of  creating the constructor for history entities by taking a parameter from the original entity :</p>
<pre class="brush: csharp;">
public Department_History(Department original):this()
{
this.IDDepartment=original.IDDepartment;
this.Name=original.Name;
}
</pre>
<p>How it do this magic ? Simple : the ModelHistory.tt  recognize the model and  history in the name of tables:</p>
<pre class="brush: csharp;">&lt;/pre&gt;
string inputFile = @&quot;Model1.edmx&quot;;
string History = &quot;_History&quot;;
&lt;pre&gt;</pre>
<p>then it generate code for constructor :</p>
<pre class="brush: csharp;">
	#&gt;
		public &lt;#=code.Escape(entity)#&gt;():base()
		{
		}
		public &lt;#=code.Escape(entity)#&gt;(&lt;#=NameEntityOriginal #&gt; original):this()
		{
		&lt;#
	foreach (EdmProperty edmProperty in entityOriginal.Properties.Where(p =&gt; p.TypeUsage.EdmType is PrimitiveType &amp;&amp; p.DeclaringType == entityOriginal))
	{
		#&gt;
				this.&lt;#= code.Escape(edmProperty.Name) #&gt;=original.&lt;#= code.Escape(edmProperty.Name) #&gt;;
		&lt;#

	}
	#&gt;
		}
	&lt;#
&lt;/pre&gt;
</pre>
<p>Ok, and then how to create the history entity ? I wish that the POCO template has had an event &#8220;Database saving&#8221; &#8211; but the only thing I can have is SaveChanges from the ObjectContext &#8211; so I create a new ObjectContext , derived from the default one that comes with the project, and creates a new history object :</p>
<pre class="brush: csharp;">

public override int SaveChanges(SaveOptions options)
{
this.DetectChanges();
DateTime dtModified=DateTime.Now;
string UserModified=clsUser.UserName;
foreach (ObjectStateEntry ose in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified))
{

//could do this way too
//if (ose.Entity != null &amp;&amp; ose.Entity.GetType() == typeof(...))
//{
//}
if (ose.Entity != null)
{
string NameType=ose.EntitySet.ElementType.Name;

switch(NameType)
{

case &quot;Department&quot;:
var itemDepartment_History = new Department_History(ose.Entity as Department);
//if compile error here, that means you keep tracking
//of which modified with another properties
//please modify the tt accordingly
itemDepartment_History.ModifiedType= ose.State.ToString();
itemDepartment_History.ModifiedDate= dtModified;
itemDepartment_History.ModifiedBy= UserModified;
base.Department_History.AddObject(itemDepartment_History);
break;

case &quot;Employee&quot;:
var itemEmployee_History = new Employee_History(ose.Entity as Employee);
//if compile error here, that means you keep tracking
//of which modified with another properties
//please modify the tt accordingly
itemEmployee_History.ModifiedType= ose.State.ToString();
itemEmployee_History.ModifiedDate= dtModified;
itemEmployee_History.ModifiedBy= UserModified;
base.Employee_History.AddObject(itemEmployee_History);
break;

}
}
}

return base.SaveChanges(options);
}
</pre>
<p>Now all is ready and I made a console application for testing manually (ok, should make a NUnit / MSTest / xUnit )</p>
<pre class="brush: csharp;">
 using (var ctx = new testsEntitiesHistory())
            {
                var dep = new Department();
                dep.Name = &quot;IT&quot;;
                ctx.Departments.AddObject(dep);
                ctx.SaveChanges();
                id = dep.IDDepartment;
            }
            using (var ctx = new testsEntitiesHistory())
            {
                var dep = ctx.Departments.Where(depart =&gt; depart.IDDepartment == id).FirstOrDefault();
                dep.Name = &quot;Information tehnology&quot;;
                ctx.SaveChanges();
                //
            }
            using (var ctx = new testsEntitiesHistory())
            {
                var dep = ctx.Departments.Where(depart =&gt; depart.IDDepartment == id).FirstOrDefault();
                ctx.Departments.DeleteObject(dep);
                ctx.SaveChanges();

            }
            using (var ctx = new testsEntitiesHistory())
            {
                foreach (var dephist in ctx.Department_History)
                {
                    Console.WriteLine(&quot;Found {0} with state {1}&quot;, dephist.Name,dephist.ModifiedType);
                }
            }
</pre>
<p>And the output is :</p>
<div id="attachment_317" class="wp-caption alignnone" style="width: 679px"><a href="http://msprogrammer.serviciipeweb.ro/wp-content/uploads/2010/06/console.png"><img class="size-full wp-image-317" title="console" src="http://msprogrammer.serviciipeweb.ro/wp-content/uploads/2010/06/console.png" alt="history saving" width="669" height="210" /></a><p class="wp-caption-text">automatically saving history department</p></div>
<p>Now you can add more tables to the edmx or change the fields &#8211; all is done automatically when compiling</p>
<p>If you want to see in action , please  download code <a href="http://msprogrammer.serviciipeweb.ro/wp-content/uploads/2010/06/history.zip">history</a></p>
<p>Update : for another way to do it( generating trigger and tables ) please see : <a href="http://msprogrammer.serviciipeweb.ro/2010/09/27/generating-history-trigger-with-ef-edmx-and-tt-files/" target="_blank">http://msprogrammer.serviciipeweb.ro/2010/09/27/generating-history-trigger-with-ef-edmx-and-tt-files/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://msprogrammer.serviciipeweb.ro/2010/06/28/ef-automatic-history-of-table-and-t4-files-tt-files/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

