Tuesday, January 31, 2006

.norm insert usage

The DataGateway class is the facade to the .norm framework. Insert, Update, Delete, and Find are all completed by using the DataGateway class. The DataGateway class has only one requirement, an instance of type IConnectionInfo. The ConnectionInfo class is a simple data object that contains the data source, catalog, user, and password of the database you are attempting to use. All of the data elements of the ConnectionInfo class are required constructor arguments.

Using DataGateway to insert data can be accomplished by doing exactly what you would expect.
Foo user = new Foo();
user.FirstName = "Jay";
user.lastName = "Fields";
user.ID = 0;

ConnectionInfo info = new ConnectionInfo("data_source","my_catalog","user_name","password");
DataGateway gateway = new DataGateway(info);
gateway.Insert(user);
In this example you are inserting an instance of type Foo into the database. Foo is designed as follows.
namespace Example
{
public class Foo
{
public int ID;
private string firstName;
private string lastName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
}
.norm uses reflection to persist the instance of the Foo class to a table named Example.Foo. By default .norm uses a type's FullName as the table name to persist an instance to. .norm also assumes that the columns of the Example.Foo table have the names ID, FirstName, and LastName. Again, reflection is used to map the values of public fields and properties to columns of the same name.

Additionally, if you need to customize the table and column names .norm uses attributes for object mapping.

Assume you want to put the same Foo object into a table named foo_user_data. Also, assume the columns in foo_user_data are f_name, l_name, and id. The insert code will remain exactly the same, but the definition of the Foo class will need to include attributes that specify the mapping names.
namespace Example
{
[RelationalMapped("foo_user_data")]
public class Foo
{
[Column("id")]
public int ID;
private string firstName;
private string lastName;

[Column("f_name")]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}

[Column("l_name")]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}
}
After making these additions to the Foo class it will be persisted to foo_user_data table when Insert is executed. Note, despite the fact that the ID column did not need a different name specified, you must explicitly specify each member that needs to be persisted on a class decorated with the RelationalMapped attribute.

2 comments:

  1. Anonymous10:30 PM

    This is a great way to solve the ORM.

    Can you implement nOrm using Windows Authentication?

    ReplyDelete

Note: Only a member of this blog may post a comment.