NHibernate returning duplicate rows
NHibernate appears to be returning the contents of the first row multiple times. As many times as there are actual, distinct rows in the database. For example, if one person has 3 campus affiliations like this:
Baker College - Teacher
Bryant Elementary - Teacher Ohio State University - StudentNHibernate will return it like this:
Baker College - Teacher
Baker College - Teacher Baker College - TeacherI'm using FluentNHibernate. Here are some snippets of the entity and mapping files:
public class Person
{
public virtual string SysID { get; set; }
public virtual string FullName { get; set; }
public virtual ICollection<Campus> Campuses { get; set; }
}
public class Campus
{
public virtual string SysID { get; set; }
public virtual string Name { get; set; }
public virtual string Affiliation { get; set; }
}
public class PersonMapping
{
Table("Person");
Id(x => x.SysId);
Map(x => x.FullName).Column("FULL_NAME");
HasMany(x => x.Campuses).KeyColumn("SysId");
}
public class CampusMapping
{
Table("Campus");
Id(x => x.SysID);
Map(x => x.Name);
Map(x => x.Affiliation);
}
I'm iterating through the campuses in my view (MVC 3) like this:
@foreach(var campus in Model.Campuses)
{
@campus.Name @campus.Affiliation
}
I also tried adding this to the entity to make sure 开发者_如何学JAVAit wasn't a silly mistake with MVC or Razor and had the same result:
public virtual string campusesToString
{
get
{
string s = "";
for (int i = 0; i < Campuses.Count; i++)
{
s = s + Campuses.ElementAt(i).Name + " ";
}
return s;
}
}
Finally, I checked the SQL that was being output, and it's correct, and it's returning all of the rows uniquely...
Your mapping looks a bit weird.
First you set up this relationship: Person 1 -> * Campus
But in your mapping of Campus you make SysId primary key, but it is also the foreign key to Person? I think that is what confuses NHibernate..
What I think happens is that NHibernate sees the same SysId key multiple times and since it will resolve the same object for the same primary key to preserve object indentity it will return the same Campus object multiple times even though the other columns have different data.
You might want to use a many-to-many mapping as otherwise each Campus will only be able to have one person which seems wrong.
Ok. I found out my problem. I was indicating the Id in the mapping incorrectly.
There is one person and multiple campuses. The person ID is called SysID. It is also the foreign key on campus. But SysID is not the unique ID for campus. NHibernate was confused because it was trying to use the person unique ID for the campus ID.
public class Campus
{
public virtual string CampusID { get; set; }
public virtual string SysID { get; set; }
public virtual string Name { get; set; }
public virtual string Affiliation { get; set; }
}
public class CampusMapping
{
Table("Campus");
Id(x => x.CampusID);
Map(x => x.SysID);
Map(x => x.Name);
Map(x => x.Affiliation);
}
精彩评论