![](/img/trans.png)
[英]How to Subselect using NHibernate 2 and Fluent mapping with alias
[英]Mapping a collection to a subselect with Fluent nHibernate
我有一堂课,看起来像:
public class Competitor
{
public virtual int CompetitorId { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual IEnumerable<string> SportsCompeted { get; set; }
}
SportsCompeted
是按以下方式解析的SportID(字符串)的列表:
SELECT DISTINCT SportID FROM results WHERE competitorId = xxx
我将如何映射类似的东西?
查看HasMany,我可以指定Where
子句,但是在这种情况下,我认为这不是我想要的吗?
我正在使用Fluent Mapping,为简洁起见,省略了它。
您应该能够使用.Element()
做到这一点。 就像是:
HasMany(x => x.SportsCompeted)
.KeyColumn("CompetitorId")
.Element("SportID") // You can define element type as second parameter
.Table("results");
更多信息:
用NHibernate映射字符串集合
流利的NHIbernate List <string>自动映射?
编辑:
假设您拥有Result
和Sport
实体:
public class Sport
{
public virtual int SportId { get; set; }
// Other properties
}
public class Result : Entity
{
public virtual ResultId { get; set; }
public virtual Competitor Competitor { get; set; }
public virtual Sport Sport { get; set; }
// Other properties
}
public class Competitor
{
public virtual int CompetitorId { get; set; }
public virtual IList<Result> Results { get; set; }
// Other properties
}
您的HasMany
现在看起来像这样:
// For this, you would need to have Result and Sport classes mapped
// This property isn't necessary for your Sports Competed query
HasMany(x => x.Results)
.KeyColumn("CompetitorId")
.Table("results");
然后,您可以使用ie。 Linq获得所需的结果:
var sports = session.Query<Result>()
.Where(x => x.Competitor.CompetitorId = competitorId)
.Select(x => x.Sport) // Or .Select(x => x.Sport.SportId)
.Distinct();
我最终要做的是在SQL中创建一个View,基本上可以这样做:
SELECT DISTINCT SportID, CompetitorID FROM results
然后,在我的映射中:
HasMany(x => x.CompetitorDisciplines)
.Not.LazyLoad()
.Inverse()
.AsBag()
.KeyColumn("competitorId")
.Element("DisciplineCode")
.Table("vCompetitorDisciplines");
这似乎产生了预期的结果。
速度很慢,但是只有一次(或每天一次)操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.