How to Map a VIEW without unique identifing column with Fluent Nhibernate - nhibernate

i have readonly VIEWs in an existing Database and i'd like to get them with FHN. i tried mapping it the following way:
public class HhstMap : ClassMap<Hhst>
{
public HhstMap()
{
Table("HHST");
ReadOnly();
Id();
Map(x => x.Hkz);
Map(x => x.Kapitel);
Map(x => x.Titel);
Map(x => x.Apl);
Map(x => x.Hhpz);
}
}
but i got an error:
could not execute query
[ SELECT this_.id as id3_0_, this_.Hkz as Hkz3_0_, this_.Kapitel as Kapitel3_0_, this_.Titel as Titel3_0_, this_.Apl as Apl3_0_, this_.Hhpz as Hhpz3_0_ FROM HHST this_ ]
this is ok cause there is no ID Column, but how can i do mapping with Fluent without the ID?

You could retrieve the records as value objects (non-managed entities) instead of entities.
"14.1.5. Returning non-managed entities
It is possible to apply an IResultTransformer to native sql queries. Allowing it to e.g. return non-managed entities.
sess.CreateSQLQuery("SELECT NAME, BIRTHDATE FROM CATS")
.SetResultTransformer(Transformers.AliasToBean(typeof(CatDTO)))
This query specified:
the SQL query string
a result transformer
The above query will return a list of CatDTO which has been instantiated and injected the values of NAME and BIRTHNAME into its corresponding properties or fields. "

Maybe this can help you: Fluent nHibernate no identity column in tableā€¦?
EDIT:
Also, you could use a composite id, or maybe you need the latest version of Fluent Nhibernate?

Related

NHIbernate "References" Property generating Select + 1 even though correctly OUTER JOINING

Ok, I am a little stumped on this NHibernate query. The confusion is around PasswordResetToken.
Firstly, here is the mapping:
public ContactMap()
{
Table("Contact");
Id(x => x.ContactId, "ContactId").Unique().GeneratedBy.Increment();
Map(x => x.EmailAddress);
...
Map(x => x.JobTitle);
References(x => x.PasswordResetToken, "EmailAddress")
.PropertyRef(x => x.EmailAddress)
.Cascade.None()
.Not.LazyLoad()
.Not.Update();
HasMany(x => x.Roles)
.Table("tblContactRole").KeyColumn("ContactId").Element("Role", part => part.Type<global::NHibernate.Type.EnumStringType<ContactRoles>>())
.AsSet()
.Not.LazyLoad();
}
Now here is the query:
public IList<Contact> GetContacts(int id)
{
var contacts = Session.CreateCriteria<Contact>()
.Add(Restrictions.Eq("Id", id))
.Add(Restrictions.Eq("IsActive", true))
.SetFetchMode("Roles", FetchMode.Eager)
.SetFetchMode("PasswordResetToken", FetchMode.Eager)
.SetResultTransformer(CriteriaSpecification.DistinctRootEntity)
.List<Contact>();
return contacts;
}
My understanding is that FetchMode.Eager means a JOIN is used instead of a SUBSELECT, so there isn't any reason there for extra calls to the db to appear.
A correct SQL query is run returning all the information required to hydrate a Contact as evidenced from the screenshot from NHProf (the highlighted query) (dont' worry about different table names etc - I have sanitized the code above):
What I don't understand is why on earth dozens of separate selects to the PasswordResetToken table are generated and run?? One of these queries is only generated for every contact that doesn't have a PasswordResetToken (ie. the first query returns nulls for those columns) - not sure what this has to do with it.
A contact might or might not have a few roles (superfluous to this issue) and similarly, may or may not have exactly one PasswordResetToken.
The DB is a little dodgy with few foreign keys. The link between Contact and PasswordResetToken in this case is a simple shared column "EmailAddress".
All these queries are generated on the running of that single line of code above (ie. that code is not in a loop).
Let me know if I am missing any info.
What should I be googling?
It's a bug. I would try to get it to work with just two queries, although from the bug report it sounds like that will be a challenge.
The attached test shows that a many-to-one association referencing an unique property (instead of the Id) results in a select n+1 problem. Although the first statement contains the correct join, all associated entities are fetched one by one after the join select. (Entities with the same value in the unique column are even fetched more than once.)
The interesting point is that this bug only occurs if the referenced
entities are already in the session cache. If they are not, no
additional select statements are created.

how to flatten a model with NHibernate

Say I have three tables Products, Languages and ProductTranslations that look like the following:
(1) ProductId
(1) StandardName
(1) Price
(2) LanguageId
(2) LanguageName
and
(3) ProductTranslationId
(3) ProductId
(3) LanguageId
(3) LocalName
(3) LocalDescription
In my object model, I need a single object (single class map) that contains the following
(3) ProductTranslationId
(2) Language
(3) LocalName
(3) LocalDescription
(1) Price
This object is only used for display, so read-only (immutable) is fine.
ProductTranslationId uniquely identifies a row.
If necessary, this object can include the LanguageID and ProductID values as well. the important feature is that this needs to include the Language and Price values from the ONE side of this one to many relationship.
I can see how to do this in 3 separate classes using Many-to-One, but how can I do this with one class, where ProductTranslationId is the <id> value?
Is there an alternative that does not require creating a view in the database?
Option 1
// FluentNHibernate Mapping
public class ProductTranslationDtoMap : ClassMap<ProductTranslationDto>
{
public ProductTranslationDtoMap()
{
ReadOnly();
Table(" ProductTranslation");
Id(x => x.Id, "ProductTranslationId");
Map(x => x.Language).Formula("(SELECT l.LanguageName FROM Language l WHERE l.LanguageId = LanguageId)"); // simple and highly portable sql formula
Map(x => x.LocalName);
Map(x => x.LocalDescription);
Map(x => x.Price).Formula("(SELECT p.Price FROM Products p WHERE p.ProductId = ProductId)");
}
}
Option 2
Product prod = null;
Language lang = null;
TranslationDto alias = null;
var results = session.QueryOver<ProductTranslation>()
.JoinAlias(pt => pt.Language, () => lang)
.JoinAlias(pt => pt.Product, () => prod)
.SelectList(list => list
.Select(pt => pt.Id).WithAlias(() => alias.ProductTranslationId)
.Select(() => lang.Name).WithAlias(() => alias.Language)
...)
.TransformUsing(Transformers.AliasToBean<TranslationDto>())
.List<TranslationDto>();
Instead of using a NHibernate mapping you could also use a class mapper like AutoMapper to create a flat representation of your complex object graph. The advantage would be one nhibernate mapping less to maintain (although the fluent variant from Firo offers compiler syntax checking) in case your db schema changes. The disadvantage of course would be speed, as you first have to make nhibernate create your complex object graph, then transform that graph into a flat object. If you only need this one flat object, you may be better of with a single NH mapping. If you think about creating several more views, a class mapper might be worth a look.

modeling ternary relationship

I'm dealing with a database schema that is err... less than ideal. The domain deals with courses. The courses have prerequisites and related courses. The db model is somthing like this:
Courses
courseid -int
code -varchar
related_courses
part_number varchar
related_part_number varchar
type int
As you might have guessed, the course and related course table is not connected vie the course pk, but instead the code column. Then the type of relationship is defined by the type column in related_course.
I would love to have a list of prerequisites and a list of related courses in my course object,but I have been unsucessfully in doing so. I'm now trying to just match the course with the related items and then filter on the type. That is not working either.
Here is my current mapping for course and course_related.
public CourseMap()
{
Map(x => x.Code);
HasMany(x => x.RelatedItems)
.Access.Property()
.PropertyRef("Code")
.KeyColumn("Part_Id");
}
public CourseRelatedMap()
{
References(x => x.Course, "part_id");
HasMany(x => x.RelatedCourses)
.Access.Property()
.KeyColumn("part_related_id");
//.PropertyRef("part_related_id");
}
When I try to query for the related courses, this is generating the correct sql for me:
SELECT relatedite0_.Part_Id as Part2_1_,
relatedite0_.CourseRelatedId as CourseRe1_1_,
relatedite0_.CourseRelatedId as CourseRe1_12_0_,
relatedite0_.part_id as part2_12_0_,
relatedite0_.Type as Type12_0_
FROM OCT_Course_Related relatedite0_
WHERE relatedite0_.Part_Id = '1632LGEE-ILT' /* #p0 */
But NH is throwing an error trying to convert a string to int, so I'm guessing that it's trying to convert relatedite0_.Part_Id = '1632LGEE-ILT' /* #p0 */ to an integer.
Any help with this would be greatly appreciated,
Try mapping Identity properties to your entities.
For CourseMap Something like this
Id(x => x.Id).Column("courseid")
I don't know if this will do it as I'm not sure I fully understood your model

Mapping a child collection without indexing based on database primary key or using bag

I have a existing parent-child relationship I am trying to map in Fluent Nhibernate:
[RatingCollection] --> [Rating]
Rating Collection has:
ID (database generated ID)
Code
Name
Rating has:
ID (database generated id)
Rating Collection ID
Code
Name
I have been trying to figure out which permutation of HasMany makes sense here. What I have right now:
HasMany<Rating>(x => x.Ratings)
.WithTableName("Rating")
.KeyColumnNames.Add("RatingCollectionId")
.Component(c => { c.Map(x => x.Code);
c.Map(x => x.Name); );
It works from a CRUD perspective but because it's a bag it ends up deleting the rating contents any time I try to do a simple update / insert to the Ratings property. What I want is an indexed collection but not using the database generated ID (which is in the six digit range right now).
Any thoughts on how I could get a zero-based indexed collection (so I can go entity.Ratings[0].Name = "foo") which would allow me to modify the collection without deleting/reinserting it all when persisting?
First of all, you're using an old version of Fluent NHibernate; WithTableName has been deprecated in favor of Table.
An IList can be accessed by index so a Bag should work. I'm not sure why you have mapped Rating as a Component or what the effect of that is. This is a standard collection mapping:
HasMany(x => x.Ratings).KeyColumn("RatingCollectionId")
.Cascade.AllDeleteOrphan().Inverse()
.AsBag().LazyLoad();

Fluent NHibnernate HasManyToMany with Index

I'm trying to map a many-to-many collection with Fluent NHibnernate. My model class has this property:
public virtual IList<Resource> Screenshots
{
get { return _screenshots; }
protected set { _screenshots = value; }
}
And my fluent mapping is:
HasManyToMany(x => x.Screenshots)
.AsList(x => x.WithColumn("Index"))
.Cascade.AllDeleteOrphan();
When I run my application, I get the following exception message:
The element 'list' in namespace
'urn:nhibernate-mapping-2.2' has
invalid child element 'many-to-many'
in namespace
'urn:nhibernate-mapping-2.2'. List of
possible elements expected: 'index,
list-index' in namespace
'urn:nhibernate-mapping-2.2'.
There should be a way to do this. Does anyone know what I am doing wrong?
The current FluentNHibernate syntax for this is as follows:
HasManyToMany(x => x.Screenshots)
.AsList(i => i.Column("`Index`"));
The index column defaults to Index, but that's a reserved word on SQL Server (and probably other databases too), so you must quote it with back-ticks.
Also, I'd recommend against setting a cascade on this relationship. Consider the following code:
x.Screenshots.Remove(s);
session.SaveOrUpdate(x);
NHibernate will correctly delete rows from the linking table even without a cascade specified. However, if you specify AllDeleteOrphan, then NHibernate will delete the row from the linking table and also delete Resource s. I doubt this is the behavior you want on a many-to-many relationship.