Reputation: 3467
Entity Photos belongs to Property entity and one property can have many photos. Mapping is fine, creating data is doing ok. In db my photos are stored for example Id 1 binarydata PropertyId(100) And Property article with Id of 100 have reference to many photos. I'm write all this to say that my creation of data is ok and mapping as well.
So, the problem is on loading photo collection on showing property details. I need to load photo collection inside session, so I'm stuck here.
public ActionResult Details(int id)
{
MyDomain.Property data = null;
using (//session)
{
using (//transaction)
{
data = session.QueryOver<MyDomain.Property>()
.Where(x => x.Id == id)
.Fetch(x => x.Photos).Eager //empty
.Fetch(x => x.Features).Eager
.SingleOrDefault<MyDomain.Property>();
//I was thinking here to call
// data.Photos = GetMyPhotos(id);
tx.Commit();
return PartialView("_HomePageDetailsPartial", data);
}
}
//return PartialView("_HomePageDetailsPartial", data);
}
As you can see in this I tried with data.Photos = GetMyPhotos(id); but on debug I have Error message Cannot update identity column 'Id'.
Cannot update identity column 'Id'.
Even this work, I'm convinced that there is some more elegant way to retrieve photos collection for particular property.
My mappings
public class PhotoMap : ClassMap<Photo>
{
public PhotoMap()
{
Table("Photo");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.ImageData).CustomSqlType("VARBINARY(MAX)").Length(160000).Not.Nullable();
Map(x => x.ImageMimeType).Not.Nullable();
References(x => x.Property).Column("PropertyId");
}
}
public class PropertyMap : ClassMap<Property>
{
public PropertyMap()
{
Table("Property");
Id(x => x.Id).GeneratedBy.Identity();
...
References(x => x.Features, "FeaturesId");
HasMany(x => x.Photos).KeyColumn("Id").Cascade.All();
}
}
DB snapshot Two tables, Property and Photo.
Id int not null
Title nvarchar(255) not null
PhotoId int not null
Photo table
Id int not null
ImageData varbinary(MAX) null
ImageMimeType varchar(50) null
PropertyId int not null
Relationship is as follows:
FK_Property_Photo
Primary Key table Foreign key table
--------------------------------------------
Photo Property
--------------------------------------------
Id PhotoId
Upvotes: 0
Views: 506
Reputation: 6023
your KeyColumn in your mapping is wrong. KeyColumn is used to define the foreign key column in the n-table. In your case, the key column should be "PropertyId".
in addition: why do you have a PhotoId column in your property table if the relation between property and photo is 1:n?
Upvotes: 4