How to Create an Entity / Object-relational Mapping
Posted by Randolph Cabral on Saturday August 4, 2007
Entities
Jammer.NET entities contain all of the mapping metadata in-line with the C# source code. We’ve found this implementation affords benefits that outweigh any incremental gains of keeping the mapping metadata in a separate file. Typically, changes made to a database schema are significant enough to require changes to the C# application source anyway. Let’s face it; how often does a requirement or feature enhancement come along that amounts to changing one column type or name? Most feature enhancements require a significant schema and application modification that necessitate a redeployment of application code even if the enhancement is as innocuous as adding a secondary email address to a web form.
Inline Metadata Mapping using Custom Attributes
Jammer.NET takes advantage of custom attributes. Custom attributes are adorned to the appropriate class members to define class member mappings as well as mappings to database objects and the database itself. The following code sample illustrates how these mappings are declared.
…
[Database("Northwind")]
[Load("usp_Customers_Get")]
[Save("usp_Customers_Insert", "usp_Customers_Update")]
[Delete("usp_Customers_Delete")]
public partial class Customers : EntityBase, IEntityValidateable
{
[Key][FieldMap("CustomerID")] private string _CustomerID;
[FieldMap("CompanyName")] private string _CompanyName;
[FieldMap("ContactName")] private string _ContactName;
[FieldMap("ContactTitle")] private string _ContactTitle;
[FieldMap("Address")] private string _Address;
[FieldMap("City")] private string _City;
[FieldMap("Region")] private string _Region;
[FieldMap("PostalCode")] private string _PostalCode;
[FieldMap("Country")] private string _Country;
[FieldMap("Phone")] private string _Phone;
[FieldMap("Fax")] private string _Fax;
…
The Database attribute defines the name of the connection instance to use which is defined in the <connectionStrings> section of the web or application configuration file. The Load, Save and Delete attributes define mappings to specific CRUD stored procedures which only are executed when base methods of the same names are invoked. The following code sample shows the application configuration file definition.
<connectionStrings>
<add name=“Northwind“ providerName=“System.Data.SqlClient“ connectionString=“server=SERVER;database=DATABASE;uid=USER;pwd=PASSWORD“ />
</connectionStrings>
The Key() Attribute
The key attribute is used to define the primary key column(s) of a given table. The usage of the key attribute is demonstrated in the following code sample.
[Key][FieldMap("CustomerID")] private string _CustomerID;
The FieldMap() Attribute
Creating mappings to columns in a table or columns returned by a stored procedure are defined by the use of the FieldMap() attribute. In the following code sample, the database column “CompanyName” is mapped to a class-level private variable “_CompanyName”. Note: FieldMap() attributes should only be used on class-level private variables.
[FieldMap("CompanyName")] private string _CompanyName;
Use Visual Studio IDE “Go To Definition” Functionality
One of the greatest benefits to using inline attribute-based mapping is the ability to use the Visual Studio IDE’s “Go To Definition” feature to navigate to the mapping definitions. This feature can be used from any tier in the code base as long as the project with the source is included in your solution. It comes in handy when you need to follow execution logic as well.
To use this feature, place the cursor at a method or property call, or variable reference and right-click. Select “Go To Definition” from the context menu and left-click. Visual Studio will open the corresponding source file and auto-scroll to the proper line where the definition is made. The image to the right is a screen capture of the context menu in Visual Studio 2005.
To return to the previous cursor location use the control-minus key stroke combination ([CTRL] + [-]). For more IDE productivity features, you can visit Microsoft’s Visual Studio Developer Center website.
Tuesday August 7, 2007 at 3:00 pm
[...] Popular Articles How to create an Entity / Object-relational MappingDownloadFAQWebcastsArchivesLegal [...]
Wednesday August 8, 2007 at 1:00 pm
[...] Articles How to Create an Entity / Object-relational MappingDownloadFAQWebcastsArchivesLegalHow to Persist Object State Over Postbacks in ASP.NET [...]
Monday May 19, 2008 at 8:03 am
I m getting an error AppSetting /Security info missing from Web config. Do i need to create these in my WebConfig file on the project.
How to create web.sitemap file and what information should be provided in there.
Monday May 19, 2008 at 8:05 am
What is the difference between JMRBusinessProjecttype and JMREntityProjecttype? Which should be selected?
Tuesday May 20, 2008 at 5:44 pm
Hi Mirza,
The security entries in the web.config file that is needed are as follows:
<add key=”SystemReturnEmail” value=”email@someaddy.com”/>
<add key=”ExceptionReturnEmail” value=”email@someaddy.com”/>
<add key=”ExceptionDeliveryEmail” value=”email@someaddy.com”/>
<add key=”DeveloperEmail” value=”email@someaddy.com”/>
<add key=”SecurityType” value=”JmrSecurity”/>
<!– SecurityType Values = None, JmrSecurity, Database, ActiveDirectory –>
The web.sitemap file should contain the following:
<?xml version=”1.0″ encoding=”utf-8″?>
<siteMap xmlns=”http://schemas.microsoft.com/AspNet/SiteMap-File-1.0″>
<siteMapNode url=”.” title=”Root” description=”Root Sitemap Node. Required By Ent.Lib.”>
<siteMapNode url=”relative path to file” value=”Allowed Roles in ActiveDirectory Security Groups or DB Roles Table. ‘*’ = access to everyone.” title=”[OPTIONAL]Title of page” description=”[OPTIONAL]Description of page” />
</siteMapNode>
</siteMap>
I hope this helps!
-Randolph Cabral
Tuesday May 20, 2008 at 5:48 pm
Hi Mirza,
The difference between the Entity project and Business project is that the Entity project is where the mappings are made. We recommend that you do not modify the Entity class as you might want to re-generate them.
The Business project is where you want to add all of your customizations. Each Business class derives from an Entity class. Because of this you can override its properties and methods giving you the ability to more closely model your domain requirements.
Hope this helps!
-Randolph Cabral
Tuesday May 20, 2008 at 8:20 pm
I m getting JmrUser Error what is the entry for Jmruser in Web Config.
if(JmrUser == null)
Response.Redirect(ConfigurationManager.AppSettings.Get(”FormLoginURL”));
Can you please give an example for entity and Business Project, will my Website Application be consuming both type of projects or will it be only one.
I m trying to write a small forum which has two tables user and post, how should I organize these two Tables in Business and entity projects.
Thank you much for your previous answers.
Wednesday May 21, 2008 at 2:49 pm
Hi Mirza,
I apologize. The reason you are getting this error is because the SecurityType entry in the web.config file is set to JmrSecurity. Please set the value to None. The errors will go away.
Here’s an example of a business entity:
public class Car : OREntities.Car
{
public Car(int id)
{
base.Id = Id;
Load();
}
public void Start()
{
if (base.FuelAmount == 0)
throw new CarEngineStartException(”You don’t have any fuel. Fill ‘er up!”);
if (base.IsEngineRunning)
throw new CarEngineStartException(”The engine is already running!”);
base.IsEngineRunning = true;
base.FuelConsumptionFactor = base.EngineSpeed * 0.04F;
}
}
You can see by this example that you have a nice place to add this type of logic. The entity layer is kept separate so that you can regenerate the entity classes if your data model changes.
In your presentation layer, you will make the reference to the Business entities so that you can call methods like Car.Start(). If you reference the Entity project you won’t have access to the Start() method.
I recommend using the code generator we’ve written to write the entities. This way you can login to the database and tell the code generator to read the tables and generate the entity classes and stored procedures. It will also generate the shell for your business classes.
Hope this is helpful.
-Randy