我有一个表团队,我有一个表位置。每个团队可以有多个位置,每个位置可以有多个团队,因此这是一个多对多的关系。
在数据库中创建此方案时,将有3个表,Team,Location和TeamLocation来保存多个到多个链接。
我使用以下内容在nhibernate中映射了这个... Team.hbm.xml
<class name="App.Data.Entities.Team,App.Data.Entities" table="`Team`" lazy="true">
<id name="Teamid" column="`TeamID`" type="Guid">
<generator class="assigned" />
</id>
<property type="string" not-null="true" length="250" name="TeamName" column="`TeamName`" />
<bag name="TeamLocations" inverse="false" table="`TeamLocations`" lazy="true" cascade="all">
<key column="`TeamID`" />
<many-to-many class="App.Data.Entities.Location,App.Data.Entities">
<column name="`LocationID`" />
</many-to-many>
</bag>
</class>
和Location.hbm.xml
<class name="App.Data.Entities.Location,App.Data.Entities" table="`Location`" lazy="true">
<id name="Locationid" column="`LocationID`" type="int">
<generator class="native" />
</id>
<property type="string" not-null="true" length="250" name="LocationName" column="`LocationName`" />
<property type="string" length="1000" name="Address" column="`Address`" />
<bag name="Teams" inverse="false" table="`TeamLocations`" lazy="true" cascade="all">
<key column="`LocationID`" />
<many-to-many class="App.Data.Entities.Team,App.Data.Entities">
<column name="`TeamID`" />
</many-to-many>
</bag>
</class>
现在我正在尝试使用条件API检索所有基于特定位置的团队,我无法...
等效的sql ...
SELECT Team.TeamName, Location.LocationName
FROM Team INNER JOIN
TeamLocations ON Team.TeamID = TeamLocations.TeamID INNER JOIN
Location ON TeamLocations.LocationID = Location.LocationID
WHERE (TeamLocations.LocationID = 2)
和asp.net代码
ICriteria criteria = _session.CreateCriteria(typeof(Team)).SetFirstResult(startRowIndex).SetMaxResults(maximumRows);
if (deptID > 0)
{
Department dept = new Department(deptID);
criteria.Add(Expression.Eq(Team.PropertyNames.Department, dept)); //for department, which works fine.
}
if (locationIDs.Count > 0)
{
List<Location> locations = new List<Location>();
foreach (int locationID in locationIDs)
{
Location loc = new Location(locationID);
locations.Add(loc);
}
criteria.CreateCriteria("TeamLocations").Add(Expression.Eq(""TeamLocations"", locations));
}
return criteria.List<Team>();
这引发错误..
could not resolve property: TeamLocations of: App.Data.Entities.Location
我无法弄清楚:(
纠正我.. 谢谢!
答案 0 :(得分:1)
您可以像我下面那样添加restriction to an association path using CreateCriteria or CreateAlias。我必须更多地了解您的模型和映射,以了解为什么您可以在Team.PropertyNames.Department上添加限制而不对其进行别名化。
ICriteria criteria = _session.CreateCriteria(typeof(Team)).SetFirstResult(startRowIndex).SetMaxResults(maximumRows);
if (deptID > 0)
{
Department dept = new Department(deptID);
criteria.Add(Expression.Eq(Team.PropertyNames.Department, dept)); //for department, which works fine.
}
if (locationIDs.Count > 0)
{
// you may need to convert locationIds to an ICollection e.g.
// var ids = locationIds.ToArray();
criteria.CreateAlias("TeamLocations", "teamLocations");
criteria.Add(Restrictions.In("teamLocations.LocationId", locationIds));
}
return criteria.List<Team>();