[英]NHibernate: Same type, different ClassMaps?
I have a use case where the same type is used in different one-to-many relationships, and the data on the many side of the relationship has to be stored to different tables depending on the usage.我有一个用例,在不同的一对多关系中使用相同的类型,并且关系的多方面的数据必须根据使用情况存储到不同的表中。 Is there a way I can tell (fluent) NHibernate which ClassMap to use (eg like my fake
UseClassMap
method below)?有没有办法告诉(流利的)NHibernate 使用哪个 ClassMap(例如,像下面我的假
UseClassMap
方法)?
Rough example code:粗略的示例代码:
public class Foo
{
public long Id {get; set;}
public IEnumerable<Bar> TheoreticalBar {get; set;}
public IEnumerable<Bar> ActualBar {get; set; }
}
public class FooMap : ClassMap<Foo>
{
Table("Foo");
Id(x => x.Id);
HasMany(x => x.TheoreticalBar).UseClassMap(TheoryBarMap);
HasMany(x => x.ActualBar).UseClassMap(ActualBarMap);
}
public class TheoreticalBarMap : ClassMap<Bar>
{
TableNames("TheoreticalBar");
...
}
public class ActualBarMap : ClassMap<Bar>
{
TableNames("ActualBar");
...
}
In the hopes of garnering more arbitrary and unexplained downvotes, I'll answer this question: I wasn't able to find a specific method to explicitly declare the ClassMap to use, but I was able to find a solution without adding unncessary subtypes or similar ClassMaps by adding a discriminator value to the child class that is set by the parent, and then using the.Where() method to filter on the discriminator value... something like this:为了获得更多任意和无法解释的反对票,我将回答这个问题:我无法找到明确声明要使用的 ClassMap 的特定方法,但我能够在不添加不必要的子类型或类似内容的情况下找到解决方案ClassMaps 通过向父设置的子 class 添加一个鉴别器值,然后使用 .Where() 方法对鉴别器值进行过滤......像这样:
class Bar
{
public string BarType {get; protected set};
public Bar(string barType)
{
BarType = barType;
}
}
public class FooMap : ClassMap<Foo>
{
Table("Foo");
Id(x => x.Id);
HasMany(x => x.TheoreticalBar).Where("BarType = theoretical");
HasMany(x => x.ActualBar).Where("BarType = actual");
}
The.Where() method allows use of string interpolation and substitutions in case you want to avoid magic strings in my simplistic example here. .Where() 方法允许使用字符串插值和替换,以防您想在我的简单示例中避免使用魔术字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.