(fluent) nhibernate conditional table mapping strategy
I have no control over d开发者_如何学JAVAatabase schema and have the following (simplified) table structure:
- CityProfile
- Id
- Name
- CountryProfile
- Id
- Name
- RegionProfile
- Id
- Name
I have a .Net enum and class encapsulating the lot:
public enum Scope { Region, Country, City }
public class Profile {
public Scope Scope { get; set; }
public int Id { get; set; }
public string Name { get; set; }
}
I am looking for a mechanism that allows me to map to the correct table, something like:
public class ProfileMap : ClassMap<Profile> {
public ProfileMap() {
switch (x => x.Scope) { // <--Invalid code here!
case Scope.City: Table("CityProfile"); break;
case Scope.Country: Table("CountryProfile"); break;
case Scope.Region: Table("RegionProfile"); break;
}
Id(x => x.Id);
Map(x => x.Name);
}
}
Or have I approached this wrong?
Given that the database schema is fixed, I would map these as 3 separate classes and map to the common interface as an any reference.
class Foo
{
public virtual IProfile Profile { get; set; }
}
public class FooMap : ClassMap<Foo>
{
public FooMap()
{
ReferencesAny(m => m.Profile)
.EntityTypeColumn("ProfileType")
.EntityIdentifierColumn("ProfileId")
.AddMetaValue<CityProfile>("CityProfile")
.AddMetaValue<CountryProfile>("CountryProfile")
.AddMetaValue<RegionProfile>("RegionProfile")
.IdentityType<int>();
}
}
精彩评论