NHibernate returning duplicate rows - nhibernate

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 - Student
NHibernate will return it like this:
Baker College - Teacher
Baker College - Teacher
Baker College - Teacher
I'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 it 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);
}

Related

Using References (many-to-one) in Fluent NHibernate creates a Foreign Key in both ends, the many end and the one-end

as the title says, I would like to create a many-to-one relationship using Fluent NHibernate. There are GroupEntries, which belong to a Group. The Group itself can have another Group as its parent.
These are my entities:
public class GroupEnty : IGroupEnty
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
...
public virtual IGroup Group { get; set; }
}
public class Group : IGroup
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
...
public virtual IGroup Parent { get; set; }
}
And these are the mapping files:
public class GroupEntryMap : ClassMap<GroupEntry>
{
public GroupEntryMap()
{
Table(TableNames.GroupEntry);
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Not.Nullable();
...
References<Group>(x => x.Group);
}
}
public class GroupMap : ClassMap<Group>
{
public GroupMap()
{
Table(TableNames.Group);
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Not.Nullable();
...
References<Group>(x => x.Parent);
}
}
With this configuration, Fluent NHibernate creates these tables:
GroupEntry
bigint Id string Name ... bigint Group_id
Group
bigint Id string Name ... bigint Parent_id bigint GroupEntry_id
I don't know why it creates the column "GroupEntry_id" in the "Group" table. I am only mapping the other side of the relation. Is there an error in my configuration or is this a bug?
The fact that "GroupEntry_id" is created with a "not null" constraint gives me a lot of trouble, otherwise I would probably not care.
I'd really appreciate any help on this, it has been bugging me for a while and I cannot find any posts with a similar problem.
Edit: I do NOT want to create a bidirectional association!
If you want a many-to-one where a Group has many Group Entries I would expect your models to look something like this:
public class GroupEntry : IGroupEntry
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
...
public virtual IGroup Group { get; set; }
}
public class Group : IGroup
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
...
public virtual IList<GroupEntry> GroupEntries { get; set; }
public virtual IGroup Parent { get; set; }
}
Notice that the Group has a list of its GroupEntry objects. You said:
I don't know why it creates the column "GroupEntry_id" in the "Group" table. I am only mapping the other side of the relation.
You need to map both sides of the relationship, the many side and the one side. Your mappings should look something like:
public GroupEntryMap()
{
Table(TableNames.GroupEntry);
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Not.Nullable();
...
References<Group>(x => x.Group); //A GroupEntry belongs to one Group
}
}
public class GroupMap : ClassMap<Group>
{
public GroupMap()
{
Table(TableNames.Group);
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Not.Nullable();
...
References<Group>(x => x.Parent);
//A Group has-many GroupEntry objects
HasMany<GroupEntry>(x => x.GroupEntries);
}
}
Check out the fluent wiki for more examples.
The solution was that I accidentally assigned the same table name for two different entities... Shame on me :(
Thanks a lot for the input though!

NHibernate ternary association with multiple values - how to map in a nice way

I've asked a similar question, but I've given up on the idea I had there to solve this problem so I would like some help solving this in a neat way instead.
I've got tables
Image - (Id, Name, RelativeFilePath)
ImageFilter - (Id, Type)
ImageContext - (Id, Name, ...)
ImageContextImage - (Id, ImageContextId, ImageId, ImageFilterId)
Example of data:
ImageContextImage Id ImageContextId ImageId ImageFilterId
1 1 1 1
2 1 1 2
3 2 1 1
4 3 2 1
As you can see, an image in a context can have several filters applied.
All of my entities are very simple, except this mapping of the above. Currently I've got
ImageContext
public virtual int Id
public virtual string Name
public virtual IList<ImageContextImage> Images
ImageContextImage
public virtual int Id
public virtual ImageContext Context
public virtual Image Image
public virtual ImageFilter ImageFilter
The above is very easy to map, but for each image I then get multiple ImageContextImage objects. I would rather have ImageContextImage contain a list of ImageFilter, so that I can simply iterate through that collection. I've tried alot of permutations of AsTernaryAssociation() and it complains that I need a Dictionary, but I want multiple values per key! Any ideas?
Any ideas? Thanks!
Ternary association can be replaced with binary associations but a new entity will appear after the replacement (Removing Ternary relationship types). It is ImageContextImage entity in your case and the hard part is to find best name for such entity. Your example is very close to this replacement.
ImageContextImage entity:
public virtual int Id { get; set; }
public virtual Image Image { get; set; }
public virtual ImageContext Context { get; set; }
public virtual IList<ImageFilter> Filters { get; set; }
and it's mapping:
Id(x => x.Id);
References(x => x.Image);
References(x => x.Context);
HasManyToMany(x => x.Filters); // filters are referenced via many-to-many relation
ImageContext entity:
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<ImageContextImage> ImageContextImageList { get; set; }
and it's mapping:
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.ImageContextImageList)
.Inverse(); // to aggregate all ImageContextImage that are fererencing this instnstance of ImageContext
.KeyColumn("Context_id");
Corresponding database schema is slightly different:
ImageContextImage(Id, Image_id, Context_id)
and new association table must be created for the many-to-many relation:
ImageFilterToImageContextImage(ImageContextImage_id, ImageFilter_id)
Note that this is only a sketch of one possible approach. Many details depends on your problem domain and must be tweaked before it is ready for production:) - e.g.cascades.
I have never used AsTernaryAssociation but it seems interesting. I will investigate it later, thank you for the inspiration:).
EDIT:
Ternary association can be implemented by slightly different mapping (using composite-element) but there is still additional entity - ImageContextImage which is mapped as component in this case:
public class ImageContext
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<ImageContextImage> ImageContextImageList { get; set; }
public ImageContext()
{
ImageContextImageList = new List<ImageContextImage>();
}
}
public class ImageContextMap : ClassMap<ImageContext>
{
public ImageContextMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.ImageContextImageList).Component(c =>
{
c.References(x => x.Image);
c.References(x => x.Filter);
}).Cascade.AllDeleteOrphan();
}
}
public class ImageContextImage
{
public virtual Image Image { get; set; }
public virtual ImageFilter Filter { get; set; }
}
ImageContext class can be extended by these methods to make things simpler:
public virtual IEnumerable<Image> AssociatedImages
{
get
{
return ImageContextImageList.Select(x => x.Image).Distinct().ToList();
}
}
public virtual IEnumerable<ImageFilter> GetFilters(Image image)
{
return ImageContextImageList.Where(x => x.Image == image).Select(x => x.Filter).ToList();
}
No success with AsTernaryAssociation.

Fluent NHibernate Relationship Mapping and Save Exception

I'm new to NHibernate and am attempting to use Fluent's AutoMapping capability so that I do not need to maintain separate XML files by hand. Unfortunately I'm running into a problem with referenced entities, specifically 'Exception occurred getter of Fluent_NHibernate_Demo.Domain.Name.Id' - System.Reflection.TargetException: Object does not match target type.
I appear to have an error in at least one of my mapping classes although they do generate the correct SQL (i.e. the created tables have the correct indexes).
The implementations for my domain models and mappings are:
Name.cs
public class Name
{
public virtual int Id { get; protected set; }
public virtual string First { get; set; }
public virtual string Middle { get; set; }
public virtual string Last { get; set; }
}
Person.cs
public class Person
{
public virtual int Id { get; protected set; }
public virtual Name Name { get; set; }
public virtual short Age { get; set; }
}
NameMap.cs
public NameMap()
{
Table("`Name`");
Id(x => x.Id).Column("`Id`").GeneratedBy.Identity();
Map(x => x.First).Column("`First`").Not.Nullable().Length(20);
Map(x => x.Middle).Column("`Middle`").Nullable().Length(20);
Map(x => x.Last).Column("`Last`").Not.Nullable().Length(20);
}
PersonMap.cs
public PersonMap()
{
Table("`Person`");
Id(x => x.Id).Column("`Id`").GeneratedBy.Identity();
References<Name>(x => x.Name.Id, "`NameId`").Not.Nullable();
// There's no exception if the following line is used instead of References
// although no constraint is created
// Map(x => x.Name.Id).Column("`NameId`").Not.Nullable();
Map(x => x.Age).Column("`Age`").Nullable();
}
Finally, the following code will produce the exception:
Name name = new Name { First = "John", Last = "Doe" };
session.Save(name);
Person person = new Person { Name = name, Age = 22 };
session.Save(person); // this line throws the exception
As mentioned, the created schema is correct but I'm unable to save using the above code. What is the correct way to create a foreign key constraint using Fluent NHibernate?
If you want to reference the name, by ID, then that's what you should do. NHibernate is smart enough to figure out what the actual FK field on Person should be and where it should point; that is, after all, the job an ORM is designed to perform.
Try this mapping:
public PersonMap()
{
Table("`Person`");
Id(x => x.Id).Column("`Id`").GeneratedBy.Identity();
References(x => x.Name, "`NameId`").Not.Nullable();
Map(x => x.Age).Column("`Age`").Nullable();
}
You've mapped the person and the name; as a result, NHibernate knows which property is the ID property of Name, and can create and traverse the foreign key on Person.

Unique key column order in fluent nhibernate

I try to create unique index with fluent nhibernate. But when i use the following classes
tables are created like :
Person Table:
Id
Name
PersonStatistic Table:
Id
Date
Count
Person_Id
Because of this structure when i create the unique key, column order look like "Date - Person_Id". But i want to column order in key like "Person_Id - Date"
Entity and map classes like below.
Entity classes :
public class Person()
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
}
public class PersonStatistic()
{
public virtual Guid Id { get; set; }
public virtual DateTime Date { get; set; }
public virtual long? Count { get; set; }
public virtual Person Person { get; set; }
}
Map classes :
public PersonMap()
{
Id(x => x.Id).GeneratedBy.GuidComb();
Map(x => x.Name).Not.Nullable().Length(50);
}
public PersonStatisticMap()
{
Id(x => x.Id).GeneratedBy.GuidComb();
Map(x => x.Date).Not.Nullable().UniqueKey("UK_Person_Date");
Map(x => x.Count).Nullable();
References(x => x.Person)
.Not.Nullable()
.UniqueKey("UK_Person_Date");
}
Something is wrong in my classes or mapping or another trick to set column order in key?
Try putting the References call before the Map one.

How do I create this reference mapping in Fluent NHibernate?

Using Fluent NHibernate I need a clue how to map my Invoice class.
public class Buyer
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string TaxRegNo { get; set; }
// .... more properties....
}
public class Invoice
{
public virtual int Id { get; set; }
public virtual int IdBuyer { get; set; }
public virtual Buyer Buyer { get; set; }
// ....more properties
}
The problem is that I want to have in Invoice class:
BuyerId - just an integer ID for reference and foregin key relationship
a copy of almost all buyer properties (its accounting document and properties cannot be changed after confirmation) - as component
I tried to this using following mapping but it doesn't work
public InvoiceMap()
{
Id(x => x.Id);
References(x => x.IdBuyer);
Component(x => x.Buyer, BuyerMap.WithColumnPrefix("buyer_"));
// ....more properties
}
You would normally not map both the foreign key and the child object. If you do map both, then do this in the mapping (or similar):
References(x => x.Buyer);
Map(x => x.IdBuyer).Column("BuyerId").Not.Insert().Not.Update();
Then you don't double up on the column name in SQL statements, which causes errors around mismatched numbers of parameters.