|
YOUR FEEDBACK
|
TOP MICROSOFT .NET LINKS Tools Microsoft .NET - Object-Relational Mapping with Codus
Let Codus do the work, while you do the thinking
By: Sean McCormack
Jul. 29, 2005 12:30 AM
Codus A good example of an ORM tool is Codus, which is free and open source. Codus is a code generator, but due to its template-based nature, it can be used to generate other forms of mappers such as nHibernate XML mappings or Gentle.NET attributes. The current version of Codus includes an out-of-the-box DAO Framework that generates all required ORM code, strongly typed collections, unit tests with mock objects, Web services, NAnt build files, and an automatically compiled VS.NET 2003 solution. Additional features include XML documentation, the creation of child properties (such as Customer.Orders), various foreign-key methods, and native ADO.NET functionality such as retrieving DataSets. Plugging in new frameworks is quite easy, since all generated code uses the NVelocity template language for its template definitions. Future versions will automatically generate mappings for frameworks such as nHibernate, iBatis, and Gentle.NET. What follows is a summary of the major pieces of Codus. ![]() GUI The GUI is a straightforward user interface that streamlines the generation process. It consists of a Project tab, which allows you to define your output location and database connection strings; a Tables tab, which allows you to select which tables and columns you want to generate and modify their properties (for example, setting a column to be a foreign key, or changing its name); and an Output tab, which is where you select which templates and features to generate. The GUI is multithreaded to improve performance and usability. SchemaBuilder One of the more difficult aspects of ORM is simply obtaining the relational information, which can then be used to generate code. The .NET framework provides two different ways to do this – via the OleDbDataReader:: GetSchemaTable method and the OleDbConnection:: GetOleDbSchemaTable method. Unfortunately, neither of these methods offers a full view of the database schema. Additionally, the GetSchemaTable call returns a weakly typed DataTable, which makes it difficult to retrieve all of the information you need. To resolve this, Codus includes a SchemaBuilder class that aggregates all schema information and builds up a DatabaseSchema object, which contains TableSchema objects. SQL Generator Because Codus works with different database platforms, to include SQL Server, Access, and Oracle (with mySQL, DB2, and Firebird around the corner), it was necessary to write a database-neutral, object-oriented API to generate code. This allows for easy future extensions without modification to the generation engine (see Listing 1). Likewise, an interface-based approach to ADO.NET was developed to decouple database code from the underlying implementations (see Listing 2). Using these two techniques, it becomes extremely easy to integrate new databases into Codus since all that’s needed is the underlying implementations for the code to generate correctly. No code changes to the base engine are needed. Template Engine The template engine is based on the excellent NVelocity template language, which was ported from Apache’s Velocity framework. NVelocity is simple to use – all you need to do is place an object in “context” with an associated key, and you can then access that object in your template. Additionally, it has common language features such as conditional logic, the ability to set variables, etc. The Codus engine provides several objects in the template context, to include the full DatabaseSchema object, along with several helper objects. Listing 3 shows an example of the NVelocity language. Originally, CodeDOM was considered for the code generation, and the earliest version of Codus used CodeDOM. Unfortunately, CodeDOM has a very verbose API and the development cycle was overly complicated. Most important, any changes had to be recompiled. With NVelocity, the templates are easy to read and changes simply require opening a file. The next time the generation engine runs, the latest template version is used. ![]() VS.NET Integration The most difficult part of Codus was developing the VS.NET integration framework. Unfortunately, VS.NET integration is via a COM-interop and is poorly documented. To further complicate things, Codus is multithreaded, which causes issues when dealing with VS.NET Automation. To make life simpler, a reusable component is embedded within Codus that handles the creation of VS.NET 2003 solutions. The configuration of the solution is driven by a single XML file that defines all of the templates, how they should be processed, and what type of project they should be added to. This allows for new templates and template projects to be added without requiring any modifications to the underlying engine or to the VS.NET Automation component. The DAO Framework As mentioned previously, Codus comes with a default template called DAO Framework, which generates all code in C#. The DAO Framework is built on the Data Access Object (DAO)/Transfer Object (TO) design pattern. A Data Access Object is generated for each table, with a corresponding Entity object that is returned containing table information. The TO is Serializable, and the DAO is a MarshalByRefObject, which allows you to use the framework in a distributed environment. Using the framework is very straightforward. Listing 4 shows some code samples that were generated for the Northwind database. Roadmap Codus is still in the early phases, with the first release out in January of this year. Moving forward, several new features are planned which should include support for other leading ORM frameworks, support for all major databases, and several improvements to the DAO Framework to include object caching and lazy loading. At any time you can download the existing application and code base from www.adapdev.com/codus. Resources
Listing 1: Using the ISelectQuery interface // Creates a sql-server specific SELECT statement // using OLEDB syntax ISelectQuery query = QueryFactory.CreateSelectQuery query.SetTable(“Employees”); query.Add(“EmployeeId”); query.Add(“FirstName”);
// [Employees] Console.WriteLine(query.GetText());
ICriteria criteria = query.CreateCriteria(); criteria.AddEqualTo(“EmployeeId”); query.SetCriteria(criteria);
// [Employees] WHERE EmployeeId = ? // If we had set the DbProviderType to // DbProviderType.SqlServer, it would instead use the // Sql Server syntax: // SELECT [EmployeeID], [FirstName] FROM [Employees] // Console.WriteLine(query.GetText());
// clause: ICriteria criteria = query.CreateCriteria(); criteria.AddEqualTo(“EmployeeId”, 1); query.SetCriteria(criteria);
// [Employees] WHERE EmployeeId = 1 Console.WriteLine(query.GetText()); Listing 2: Codus utilizes ADO.NET interfaces for database independence // Creates an OleDbConnection IDbConnection connection = DbProviderFactory.CreateConnection connection.ConnectionString = “some connection...”; Listing 3: The NVelocity language ## This code iterates through each ColumnSchema object contained in ## which was passed into context. For each column it creates a ## and its name (Employees, etc.). The $column properties such ## ColumnSchema object and can be accessed by NVelocity. ## NVelocity can also call methods, etc. #foreach($column in $tableschema.SortedColumns.Values)
get { return this.${column.MemberName};} set { this.${column.MemberName} = value;} } #end Listing 4: Using the Codus-generated code for Northwind // Get all records and print out the Employees first // name EmployeesDAO dao = new EmployeesDAO(); IList employees = dao.SelectAll(); foreach(EmployeesEntity e in employees){Console.WriteLine(e.FirstName); } // Create a new record and save EmployeesEntity employee = new EmployeesEntity(); employee.FirstName = “Joe”; employee.LastName = “Schmoe”; // ...etc.
dao.Save(employee); // Populate a DataSet EmployeesDAO dao = new EmployeesDAO(); DataSet employeesDS = dao.SelectAllDS(); // Get the number of records EmployeesDAO dao = new EmployeesDAO(); int count = dao.GetCount(); YOUR FEEDBACK
MICROSOFT .NET LATEST STORIES
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
|
SYS-CON FEATURED WHITEPAPERS MOST READ THIS WEEK BREAKING NEWS FROM THE WIRES
|
|||||||||||||||||||||||||||||||||||||