Say I have an immutable ICompositeUserType to deal with a DateRange, or Money, and then it turns out that I have another value object (ie, immutable) that has either a DateRange or Money property value in it. For example, a Name that has an EffectivePeriod (DateRange).
The DataRangeUserType encapsulates some logic I wouldn't want duplicated.
Can I reuse my DataRangeUserType inside of a NameUserType? How?
Cheers,
Berryl
UPDATE
Below is the summary comment on ICompositeUserType taken from the NHibernate source code which suggests what I am thinking of can be done, just not sure how. Admittedly, the component strategy is easy and works great, until you think you might want to use the same compoent elsewhere
/// <summary>
/// A UserType that may be dereferenced in a query.
/// This interface allows a custom type to define "properties".
/// These need not necessarily correspond to physical .NET style properties.
///
/// A ICompositeUserType may be used in almost every way
/// that a component may be used. It may even contain many-to-one
/// associations.
///
/// ...
/// </summary>
Using component mapping
<component name="MyCompositeComponent" class="...">
<property name="Name" not-null="true" length="50"/>
<property name="Price" type="...MoneyUserType">
<column name="Amount"/>
<column name="Currency"/>
</property>
<property name="EffectivePeriod" type="...DateRangeUserType">
<column name="EffectiveStart"/>
<column name="EffectiveEnd"/>
</property>
</component>
Hibernate lets you compose value types in Components:
<class name="MyClass" table="MyTable" >
...
<component name="_namedPeriod">
<property name="_name" column="PeriodName" />
<property name="_effectivePeriod"
type="MyNamespace.DataRangeUserType, MyAssembly" >
<column name="PeriodStart" />
<column name="PeriodEnd" />
</property>
</component>
...
</class>
Classes look like this:
// entity
public class MyClass {
private NamedPeriod _namedPeriod;
}
// immutable value object
public class NamedPeriod {
private readonly String _name;
// immutable value object
private readonly DateRange _effectivePeriod;
}
The idea that you use UserTypes for primitives like DateRange and Money and Component for a larger immutable value objects. Components can also include other components.
Related
I have the following class:
public class Foo
{
//...
protected int? someData;
public int? SomeData
{
get {return someData;}
set {someData = value;}
}
//...
}
This class is mapped in HBM file:
<class name="Foo" table="Foo">
//....
<property name="someData" access="field" column="SOME_DATA" />
//....
</class>
For legacy reasons, the columns were mapped to a fields (lowercase), which are unaccessible (not public properties - uppercase).
These lowercase mappings are using multiple times in the project as part of HQL strings, criteria-based queries and so on. It is close to impossible to find all usages.
The problem is that such usage makes it impossible to use even on simple lambda:
session.Query<Foo>().Select(f=>f.SomeData)
throws error, as uppercase "SomeData" is not mapped, and
session.Query<Foo>().Select(f=>f.someData)
does not compile, as lowercase "someData" is protected.
What happens, if I will map BOTH field and property:
<property name="someData" access="field" column="SOME_DATA" />
<property name="SomeData" access="property" column="SOME_DATA" />
I tried quickly, and it seems to work, but will it have any drawback?
Is there any other simple solution, that will not require editing every criteria-based query in project?
Thanks for any help.
You can map the same column multiple times but with recent NHibernate versions only one of the properties need to be mapped as modifiable. So just add insert="false" update="false" to your additional mappings to avoid any issues in future:
<property name="someData" access="field" column="SOME_DATA" />
<property name="SomeData" access="property" column="SOME_DATA" update="false" insert="false" />
I'm a fresher with the enterprise library. I want to ask some questions and any help will be appreciate.
1、 How to deploy inject an instance property.
public class MyObject
{
public MyObject(string Title)
{
///...
}
public MyObject(InjectObject injectObject)
{
///...
}
public InjectObject InjectObject{get;set;}
public List<string> MyList {get;set;}
public string Title {get;set;}
}
Now I know how to inject the default value to the title property. But how to do
with
the InjectObject and the MyList.
<register type="IMyObject" mapTo="MyObject">
<property name="Title" value="MyFirstObject">
</property>
//But how to assign or instance the InjectObject and the MyList
</register>
But how to assign or instance the InjectObject and the MyList
<register type="IMyObject" MapTo=“MyObject”>
<constructor>
<param type="string" name="title" value="MyFirstObject"/>
</constructor>
2、 How to deliver a class instance to the constructor
and I know how to assign a string value to the constructor. But how to transfer
a class instance.
How can I assign a class instance to the constructor and How if i have two constructor method to deploy.
Thank you for your help.
Best Regards.
Daivd
Firstly, prefer constructor injection over property injection.
To inject the type to the constructor, you use the <dependency [name=""] /> attribute.
For example:
<register type="IMyObject" MapTo=“MyObject”>
<constructor>
<param name="injectObject">
<dependency />
</param>
</constructor>
<register>
<register type="InjectObject" />
UPDATE:
To add an array as the injection value you need to configure something like this:
<param name="parmName">
<array>
<value value="firstValue" />
<dependency />
<value value="some other value" />
</array>
</param>
Check out the Unity configure schema for all the detail on how to do this.
My class has a field of type Dictionary<string, List<string>>. What's the best way to map it with NHibernate? I'd better leave it as a field, don't want to expose it.
Thanks a lot!
ulu
You can't directly map it. There are two rules to consider:
Always use interfaces for collections (eg. IList<T>, IDictionary<K,V>)
NH does not support nested collections. I've never seen an application for it before
and never heard someone requesting it.
Put your list of string into a class and use interfaces:
class StringList
{
IList<string> Strings { get; private set; }
}
class Entity
{
private IDictionary<string, StringList> stringDict;
}
You might even see some advantages of having such a class.
Mapping:
<class name="Entity">
...
<map name="stringDict" table="Entity_StringDict" access="field">
<key column="Entity_FK"/>
<index column="Key" type="System.String"/>
<composite-element class="StringList">
<bag name="Strings" table="Entity_StringDict_Strings">
<key column="Entity_StringDict_FK"/>
<element type="System.String" column="String"/>
</bag>
</composite-element>
</map>
</class>
Maps to three Tables:
Table Entity
Table Entity_StringDict
Column Entity_FK
Column Key
Table Entity_StringDict_Strings
Column Entity_StringDict_FK
Column String
I have a class StoreHours that has a composite key and has been working perfectly. A new demand came up for another type of hours to be returned. I thought "simple, I'll abstract the base class, have two concrete implementations and change my references in the app to one of the new classes". However, upon doing that, my unit tests failed with
X.Test.StoreTest.HoursTest: NHibernate.InstantiationException : Cannot instantiate abstract class or interface: X.Model.StoreHours
My mapping file looks like
<class name="StoreHours" table="StoreHour" abstract="true" discriminator-value="0" >
<composite-id>
<key-many-to-one name="Store"
class="Store"
column="StoreUid"/>
<key-property name="DayOfWeek"
column="DayOfWeekId"
type="System.DayOfWeek" />
</composite-id>
<discriminator column="StoreHourType" type="Byte" />
<property name="OpenMinutes" column="OpenTime" />
<property name="CloseMinutes" column="CloseTime" />
<subclass name="OfficeHours" discriminator-value="1" />
<subclass name="AccessHours" discriminator-value="2" />
</class>
I found someone with similar troubles here and started down their solution path but actually ended up with even more troubles than I started with.
I can persist the records to the database perfectly but onload, NHibernate is trying to instantiate the abstract 'StoreHours' even though I've only got a strongly type set off 'OfficeHours'
This seems like a really trivial requirement so I figure I must be doing something simple wrong. All hints appreciated.
The problem is in the way you are using the composite-id
Table-per-class works with Composite-id, but only if the composite is
implemented as a class
so you need to create a class like
public class StoreHoursCompositeId
{
public virtual Store Store { get; set; }
public virtual DayOfWeek DayOfWeek { get; set; }
// Implement GetHashCode(), is NH-mandatory
// Implement Equals(object obj), is NH-mandatory
}
In your StoreHours object create a property which use the above class (in my example I called it "StoreHoursCompositeId")
Your mapping become:
<class name="StoreHours" table="StoreHour" abstract="true" discriminator-value="0" >
<composite-id name="StoreHoursCompositeId" class="StoreHoursCompositeId">
<key-many-to-one name="Store" class="Store"
column="StoreUid"/>
<key-property name="DayOfWeek"
column="DayOfWeekId"
type="System.DayOfWeek" />
</composite-id>
<discriminator column="StoreHourType" type="Byte" />
<property name="OpenMinutes" column="OpenTime" />
<property name="CloseMinutes" column="CloseTime" />
<subclass name="OfficeHours" discriminator-value="1" />
<subclass name="AccessHours" discriminator-value="2" />
</class>
I had the very same problem and this fixed it for me.
I have a class which contains a collection of Points (PointF's rather).
I want to be able to persist instances of that class using NHibernate.
My class looks somewhat like this (simplified):
public class MyClass
{
public IDictionary<string, PointF> Points = new Dictionary<string, PointF>();
public void AddPoint( location, PointF position )
{
Points.Add(location, position);
}
}
The mapping of this collection looks like this (simplified):
<map name="Points" table="Locations">
<key column="MyClassId" />
<index column="LocationName" />
<composite-element class="System.Drawing.PointF, System.Drawing">
<property name="X" column="X" />
<property name="Y" column="Y" />
</composite-element>
</map>
The problem now is, that NHibernate throws an error while processing the mapping file, since PointF is not a known (mapped) entity.
How can I solve this in the most simple way ?
How can I make sure that NHibernate is able to persist my collection of locations (with their coordinates (point) ?
The problem is not that you didn't map the type PointF - because you map it as composite-element, which is correct.
When mapping such types you need to make sure
that properties are writable (which is luckily the case here)
that it has a default constructor, which is not the case here.
So how should NH create new instances when there is not default constructor? It can't.
Your options are:
implement an interceptor or NH event. I think it is possible to inject code there which creates instances of certain types, but I don't know how.
implement a NH user type (derived from ICompositeUserType), which is not too hard to do
map another type (eg. a wrapper to PointF)