我有一个看起来像这样的课程:
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 Mappings,为简洁起见省略。
答案 0 :(得分:1)
您应该可以使用.Element()
进行此操作。类似的东西:
HasMany(x => x.SportsCompeted)
.KeyColumn("CompetitorId")
.Element("SportID") // You can define element type as second parameter
.Table("results");
更多信息:
Mapping collection of strings with NHibernate
Fluent NHIbernate automapping of 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();
答案 1 :(得分:0)
我最终做的是在SQL中创建一个基本上做的视图:
SELECT DISTINCT SportID, CompetitorID FROM results
然后,在我的映射中:
HasMany(x => x.CompetitorDisciplines)
.Not.LazyLoad()
.Inverse()
.AsBag()
.KeyColumn("competitorId")
.Element("DisciplineCode")
.Table("vCompetitorDisciplines");
这似乎产生了预期的结果 慢,但这只是一次(或每天一次)操作......