Friday, February 03, 2006

.norm find usage

.norm allows you to easily return instances of any type from that database.

DataGateway.Find takes a type and an IWhere as parameters. The type is the type of the instance you are returning, and the IWhere specifies which record to return. If IWhere does not limit the matching records to only one, the first record returned will be used to create the result.
ConnectionInfo info = new ConnectionInfo("source","catalog","user","pass");
DataGateway gateway = new DataGateway(info);
IWhere where = new Where().Column("bar").IsEqualTo(1);
Foo foo = (Foo) gateway.Find(typeof(Foo),where);
The result will be a fully hydrated instance of the Foo class.

If the Foo class has any dependencies, those dependencies can be registered with the DataGateway.* Registering a dependency will allow .norm to use constructors that contain dependencies. The code is basically the same except the dependency registration.
ConnectionInfo info = new ConnectionInfo("fieldsj2","norm","jay","jay");
DataGateway gateway = new DataGateway(info);
gateway.RegisterComponentImplementation(typeof(MappedFactory));
IWhere where = new Where().Column("some_field").IsEqualTo(1);
MappedFind result = (MappedFind) gateway.Find(typeof(MappedFind),where);
The above code will return an instance of MappedFind with it's MappedFactory dependency already injected.
[RelationalMapped("mapped")]
private class MappedFind
{
private readonly MappedFactory factory;

public MappedFind(MappedFactory factory)
{
this.factory = factory;
}

[Column("some_field")]
public int Field = 0;
private string prop;

[Column("some_prop")]
public string Property
{
get { return prop; }
set { prop = value; }
}

public int FactoryGet()
{
return factory.ReturnSix();
}
}

private class MappedFactory
{
public int ReturnSix()
{
return 6;
}
}
*DataGateway is actually delegating the registration to a PicoContainer instance. This instance is also used for creating the objects that are returned from the database.

No comments:

Post a Comment

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