How to add many-to-many relation using stateless session in NHibernate? - nhibernate

I have two entities mapped to DB using NHibernate:
class Entity1
{
public int Id { get; set; }
public Entity2[] ReferencedEntities { get; set; }
}
class Entity2
{
public int Id { get; set; }
}
For Entity1 I also specify many-to-many relation to Entity2:
HasManyToMany(x => x.ReferencedEntities);
As I understand, internally NHibernate represents many-to-many relation creating some relation entity like:
class Reference
{
public Entity1 Entity1 { get; set; }
public Entity2 Entity2 { get; set; }
}
I'm adding those entities to DB using NHibernate stateless session like this:
using (var session = sessionFactory.OpenStatelessSession())
{
session.Insert(entity1);
foreach (var entity2 in entity1.ReferencedEntities)
{
session.Insert(entity2);
}
}
But I also want to add relation between them. For this, I need to save relation entity as well. How can I add many-to-many relation using stateless session? Do I need to specify relation entity implicitly or there is some another way?

Stateless session doesnt cascade operations so it wont save changes and links to the arrayelements if they are performed in other tables.
Unnecessary selects are often a sign of missing/wrong code like UnsavedValue() or Equals()``GetHashCode()

Related

One-to-one entity framework

I am doing the entity framework code first to set up my database.
I have two classes where their relationships are one-to-one, Lecturer & LoginInfo.
public class Lecturer
{
public int LecturerId { get; set; }
public string FullName { get; set; }
public int UserId { get; set; }
public LoginInfo LoginInfo { get; set; }
}
public class LoginInfo
{
public int UserId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool ChangePassword { get; set; }
public Lecturer Lecturer { get; set; }
}
So for my entity framework, I have written this for the one-to-one relationship.
modelBuilder.Entity<Lecturer>()
.HasOne(input => input.LoginInfo)
.WithOne(input => input.Lecturer)
.HasForeignKey<Lecturer>(input => input.UserId);
From the code above, does it mean that Lecture has one LoginInfo, LoginInfo with one Lecturer and Lecturer has a UserId as a foreign key?
Another question would be, for this one to one relationship, do I have to write another set of code for LoginInfo like this:
modelBuilder.Entity<LoginInfo>()
.HasOne(input => input.Lecturer)
.WithOne(input => input.LoginInfo)
.HasForeignKey<LoginInfo>(input => input.LecturerId);
I am just a beginner trying to learn, thanks for helping :).
From the code above, does it mean that Lecture has one LoginInfo, LoginInfo with one Lecturer and Lecturer has a UserId as a foreign key?
Correct. It also means that LoginInfo is the principal and Lecturer is the dependent end of the relationship. Also since the FK property is not nullable, the relationship is required, i.e. in order to create Lecturer you have to create LoginInfo first, which is not associated with another Lecturer.
Also note that since the UserId is not following the default convention for PK name, you should explicitly configure it as PK of the LoginInfo:
modelBuilder.Entity<LoginInfo>()
.HasKey(e => e.UserId);
Another question would be, for this one to one relationship, do I have to write another set of code for LoginInfo like this
No. Single relationship requires single configuration and single FK. If you do so, you would be defining a second relationship, which also would create circular dependency between the entity, which should be avoided in general. The first fluent configuration fully defines the desired relationship and is enough to handle loading related data and other CRUD operations.
For more info about terms, relationship types and configuration, see Relationships section of the EF Core documentation.

Fluent Nhibernate Cascade.None() results in HasOne foreign key relationship not being persisted

I'm having issues with Nhibernate persisting a HasOne Relationship for one of my entities with Cascade.None() in effect. My domain model involves 4 classes listed below.
public class Project
{
public virtual int Id {get;set;}
public virtual IList<ProjectRole> Team { get; protected set; }
}
public class ProjectRole
{
public virtual int Id { get; set; }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}
public class Role
{
public virtual int Id { get; set; }
public virtual string Value { get; set; }
}
public class User
{
public virtual int Id { get; protected set; }
public virtual string LoginName { get; set; }
}
So basically we have projects, which have a list of ProjectRoles available from the Team property. Each ProjectRole links a User to the specific Role they play on that project.
I'm trying to setup the following cascade relationships for these entities.
project.HasMany<ProjectRoles>(p=> p.Team).Cascade.All()
projectRole.HasOne<Role>(r => r.Role).Cascade.None()
projectRole.HasOne<User>(r => r.User).Cascade.SaveUpdate()
I've used fluent nhibernate overrides to setup the cascades as above, but I'm finding that the line
projectRole.HasOne<Role>(r => r.Role).Cascade.None()
is resulting in the ProjectRole.Role property not being saved to the database. I've diagnosed this be looking at the SQL Generated by Nhibernate and I can see that the "Role_id" column in the ProjectRoles table is never set on update or insert.
I've also tried using
projectRole.HasOne<Role>(r => r.Role).Cascade.SaveUpdate()
but that fails as well. Unfortunately leaving it Cascade.All() is not an option as that results in the system deleting the Role objects when I try to delete a project role.
Any idea how to setup Cascade.None() for the ProjectRole-> Role relationship with out breaking persistence.
HasOne is for a one-to-one relationship which are rare. You want to use References to declare the one side of a one-to-many relationship. Making some assumptions about your domain model, the mapping should look like:
project.HasMany<ProjectRoles>(p=> p.Team).Inverse().Cascade.AllDeleteOrphan()
projectRole.References<Role>(r => r.Role);
projectRole.References<User>(r => r.User);
See also this question about the difference between HasOne and References.

Entity Framework Code First Class with parent and children of same type as it's own class

I have a class of Content which should be able to have a parentId for inheritance but also I want it to have a list of child content which is nothing to do with this inheritance tree.
I basically wanted a link table as ChildContentRelationship with Id's for parentContent and childContent in it and the Content class would have a list of ChildContentRelationship.
This has caused a lot of errors.
Here's waht I sort of want to do
public class Content
{
public int Id { get; set; }
public int? ParentContentId { get; set; }
public virtual Content ParentContent { get; set; }
public string Name { get; set; }
public int ContentTypeId { get; set; }
public virtual ContentType ContentType { get; set; }
public virtual ICollection<Property> Properties { get; set; }
public virtual ICollection<ChildContentRelationship> ChildContent { get; set; }
}
How would I set this up in EF?
I am not sure if I understand your model correctly. Let's discuss the options.
For a moment I omit this additional entity ChildContentRelationship and I assume the ChildContent collection is of type ICollection<Content>.
Option 1:
I assume that ParentContent is the inverse property of ChildContent. It would mean that if you have a Content with Id = x and this Content has a ChildContent with Id = y then the ChildContents ParentContentId must always be x. This would only be a single association and ParentContent and ChildContent are the endpoints of this same association.
The mapping for this relationship can be created either with data annotations ...
[InverseProperty("ParentContent")]
public virtual ICollection<Content> ChildContent { get; set; }
... or with Fluent API:
modelBuilder.Entity<Content>()
.HasOptional(c => c.ParentContent)
.WithMany(c => c.ChildContent)
.HasForeignKey(c => c.ParentContentId);
I think this is not what you want ("...has nothing to do with..."). Consider renaming your navigation properties though. If someone reads Parent... and Child... he will very likely assume they build a pair of navigation properties for the same relationship.
Option 2:
ParentContent is not the inverse property of ChildContent which would mean that you actually have two independent relationships and the second endpoint of both relationships is not exposed in your model class.
The mapping for ParentContent would look like this:
modelBuilder.Entity<Content>()
.HasOptional(c => c.ParentContent)
.WithMany()
.HasForeignKey(c => c.ParentContentId);
WithMany() without parameters indicates that the second endpoint is not a property in your model class, especially it is not ChildContent.
Now, the question remains: What kind of relationship does ChildContent belong to? Is it a one-to-many or is it a many-to-many relationship?
Option 2a
If a Content refers to other ChildContents and there can't be a second Content which would refer to the same ChildContents (the children of a Content are unique, so to speak) then you have a one-to-many relationship. (This is similar to a relationship between an order and order items: An order item can only belong to one specific order.)
The mapping for ChildContent would look like this:
modelBuilder.Entity<Content>()
.HasMany(c => c.ChildContent)
.WithOptional(); // or WithRequired()
You will have an additional foreign key column in the Content table in your database which belongs to this association but doesn't have a corresponding FK property in the entity class.
Option 2b
If many Contents can refer to the same ChildContents then you have a many-to-many relationship. (This is similar to a relationship between a user and roles: There can be many users within the same role and a user can have many roles.)
The mapping for ChildContent would look like this:
modelBuilder.Entity<Content>()
.HasMany(c => c.ChildContent)
.WithMany()
.Map(x =>
{
x.MapLeftKey("ParentId");
x.MapRightKey("ChildId");
x.ToTable("ChildContentRelationships");
});
This mapping will create a join table ChildContentRelationships in the database but you don't need a corresponding entity for this table.
Option 2c
Only in the case that the many-to-many relationship has more properties in addition to the two keys (ParentId and ChildId) (for example something like CreationDate or RelationshipType or...) you would have to introduce a new entity ChildContentRelationship into your model:
public class ChildContentRelationship
{
[Key, Column(Order = 0)]
public int ParentId { get; set; }
[Key, Column(Order = 1)]
public int ChildId { get; set; }
public Content Parent { get; set; }
public Content Child { get; set; }
public DateTime CreationDate { get; set; }
public string RelationshipType { get; set; }
}
Now your Content class would have a collection of ChildContentRelationships:
public virtual ICollection<ChildContentRelationship> ChildContent
{ get; set; }
And you have two one-to-many relationships:
modelBuilder.Entity<ChildContentRelationship>()
.HasRequired(ccr => ccr.Parent)
.WithMany(c => c.ChildContent)
.HasForeignKey(ccr => ccr.ParentId);
modelBuilder.Entity<ChildContentRelationship>()
.HasRequired(ccr => ccr.Child)
.WithMany()
.HasForeignKey(ccr => ccr.ChildId);
I believe that you want either option 2a or 2b, but I am not sure.

NHibernate and "anonymous" entities

I have these entities:
public class Parent
{
public int Foo { get; set; }
public Child C { get; set; }
}
public class Child
{
public string Name { get; set; }
}
I have query which fetches all Parent entities from the database. Then I keep them in memory, and filter them using LINQ queries.
I have noticed that when I do the DB query, NH selects all the Parent entities in one query (and of course fills the Foo property), and for each Parent I access with LINQ, NH fetches the infos of each Child.
How can I do to fetch all infos I need in one unique DB, and use the data with LINQ without it to generate additional DB trips?
Should I use the AliasToBeanResultTransformer? If so, must I create a DTO which will store the infos, like:
public class ParentDTO
{
public int Foo { get; set; }
public string ChildName { get; set; }
}
or must I still use the Parent class?
Thanks in advance
You can eagerly load the children for this query like this (using QueryOver syntax)
public IList<Parent> FindAllParentsWithChildren()
{
ISession s = // Get session
return s.QueryOver<Parent>()
.Fetch(p => p.C).Eager
.List<Parent>();
}
An alternative is to change your HBM files to indicate that Child is eagerly loaded by default. Then you won't need to alter your query.
You need to tell NHibernate not to use lazy loading for the relationship between the Parent and Child entities.

Fluent Nhibernate How to specify Id() in SubclassMap

I'm in the process of adapting Fluent NHibernate to our existing legacy app and am trying to determine how to use ClassMap and SubclassMap for the entity hierarchy shown.
// BaseObject contains database columns common to every table
public class BaseObject
{
// does NOT contain database id column
public string CommonDbCol1 { get; set; }
public string CommonDbCol2 { get; set; }
// ...
}
public class Entity1 : BaseObject
{
public int Entity1Id { get; set; }
// other Entity1 properties
}
public class Entity2 : BaseObject
{
public int Entity2Id { get; set; }
// other Entity2 properties
}
The identity columns for Entity1 and Entity2 are uniquely named per table. BaseObject contains columns that are common to all of our entities. I am not using AutoMapping, and thought I could use ClassMap on the BaseObject, and then use SubclassMap on each Entity like this:
public class Entity1Map : SubclassMap<Entity1>
{
public Entity1Map()
{
Id(x => x.Entity1Id);
// ...
}
}
Problem is, Id() is not defined for SubclassMap. So, how do I specify within each Entity1Map, Entity2Map, ... (we have 100+ entity classes all inheriting from BaseObject) what the entity-specific Id is?
Thanks in advance for any insight!
It's not possible to do that in either Fluent NHibernate or NHibernate. Do you actualy want your classes to be mapped as subclasses, or do you just want them to share the common mappings? If you truly want subclasses, then you're going to need to have them share the identity column, no other way around it; if you don't want actual subclasses, create an abstract ClassMap<T> where T : BaseObject and map the common properties in there.
Something like:
public abstract class BaseObjectMap<T> : ClassMap<T> where T : BaseObject
{
public BaseObjectMap()
{
Map(x => x.CommonProperty1);
}
}