Complex mapping of columns and tables in NHibernate
I have a rather simple Database:
table NamedItem
Columns: Id (PK) Country (string) Category (string) MainName (string)table AlternateNames
Columns: NamedItemId (FK to NamedItem.Id) AlternateName (string)I want to have the following classes and enums to map to these two tables:
enum Country {Germany, England, Spain} //Name of enum value and country string in DB have to be the same
enum Category {A, B, C} //Name of enum value and category string in DB have to be the same class Item { Guid ID {get;set;} ItemNames Names {get;set;}} class ItemNames { string MainName {get;set;} IList<
string>
AlternateNames {get; set;}}
UPDATE:
The important thing is not the enums but that class ItemNames that contains parts from two different tables and is located in the entity of one of those t开发者_如何学JAVAables.Is this possible with NHibernate, preferably with Fluent NHibernate?
If so, please give me a jump start. I couldn't figure out, how to do it.Kind regards,
Daniel
P.S. I posted the same question in the Microsoft Entity Framework forum, asking whether it is possible with EF4. Depending on the answers, I will choose the framework I will use. Just in case someone is wondering...
Just map the class up as if it was a normal string datatype. NH will call the ToString method of the value in effect saving the text value of the enum to the database.
so you mapping might look something like:
public partial class ItemMap : ClassMap< Item >
{
Table( "NamedItem" ) ;
Id(x => x.Id, "Id" )
.Not.Nullable()
.GeneratedBy.Guid();
Map( x => x.Country )
.Column( "Country" )
.Not.Nullable( )
.Length( 255 ) ;
Map( x => x.Category )
.Column( "Category" )
.Not.Nullable( )
.Length( 255 ) ;
...
HasMany< ItemName >( x => x.ItemNames )
.KeyColumns.Add( "NamedItemId" )
.Table( "AlternateNames" )
.LazyLoad( )
.Cascade.None( )
.AsSet() ;
...
}
and a class similar to
public class Item
{
public virtual Guid Id { get; set; }
public virtual CountryType Country { get; set; }
public virtual CategoryType Category { get; set; }
...
public virtual ISet< ItemNames > AlternateNames {get; set;}
...
}
I have the collection set to a set as that stops duplicates being in the collection which can sometimes cause issues.
精彩评论