Fluent NHibernate Mapping Compent with Many-To-Many and Extra Fields - nhibernate

I have been spinning around in the same place trying to figure this issue with a many-to-many table with extra columns. I am swallowing my pride and asking more experienced Fluent NHibernate experts if you can help out here.
I have been trying to use a component for a many-to-many table but I don't seem to find where to point the component to cause a join on a specific column. I guess as long as I populate the completion information object, the presence and usage of a component is not a requirement for me.
This is my simplified schema.
User
...................
Id
Name
Task
...................
Id
Name
Job
...................
Id
Name
JobTask
...................
JobId
TaskId
CompletedByUserId
CompletionDate
CompletionNotes
Then I have objects like so:
public class Job
{
long Id { get; set; }
IList<Task> Tasks { get; set; }
}
public class Task
{
long Id { get; set; }
string Name { get; set; }
CompletionInfo CompletionInfo { get; set; }
}
public class CompletionInfo
{
User User { get; set; }
DateTime CompletionDate { get; set; }
}
Can you help with your ideas how to implement this in fluent nhibernate?
I had this mapping before on the JobMap and it would work but only for the many-to-many columns ( TaskId, JobId). I need the extra information related to that relationship(dateCompleted, userCompleted,etc)
HasManyToMany<Task>(job => job.Tasks)
.Table(ManyToManyTable)
.ParentKeyColumn("JobId")
.ChildKeyColumn("TaskId")
.Not.LazyLoad()
.Cascade.Delete();
In order to simplify things with the many-to many I thought to create an object to represent the relationship and encapsulate a task. Like so:
And I would add a proxy in the Job task to modify the actual Task properties. But that is not going anywhere.
This must be something common out there, I am very surprised there not much regarding this issue.
Naturally I would have loved a way to extend the HasManyToMany but not sure how, hence this post.
public class JobTask : Entity<long, JobTask>
{
public virtual Job ParentJob { get; set; }
public virtual Task Task { set;set; }
public virtual TaskCompletionDetails CompletionInformation
{
get
{
if (this.Task == null)
return null;
return Task.CompletionInformation;
}
set
{
if (this.Task == null)
return;
this.Task.CompletionInformation = value;
}
}
public virtual string CompletionNotes
{
get
{
if (this.Task == null || this.Task.CompletionInformation == null)
return null;
return Task.CompletionInformation.Notes;
}
set
{
if (this.Task == null)
return;
this.Task.CompletionInformation.Notes = value;
}
}
public virtual DateTime? CompletionDate
{
get
{
if (this.Task == null || this.Task.CompletionInformation == null)
return null;
return Task.CompletionInformation.Date;
}
set
{
if (this.Task == null)
return;
this.Task.CompletionInformation.Date = value;
}
}
public virtual IUser User
{
get
{
if (this.Task == null || this.Task.CompletionInformation == null)
return null;
return Task.CompletionInformation.User;
}
set
{
if (this.Task == null || value == null)
return;
if (this.Task.CompletionInformation != null)
this.Task.CompletionInformation.User = value;
}
}
}
}
This would be the map direction I have started for it:
public class JobTaskMap : ClassMap<JobTask>
{
private const string ModelTable = "[JobTasks]";
public JobTaskMap()
{
Table(ModelTable);
Id(jobTask => jobTask.Id)
.Column("Id")
.GeneratedBy.Identity();
References<Job>( jobTask => jobTask.ParentJob)
.Column("JobId")
.Fetch.Join();
Component<Task>( jobTask => (Task) jobTask.Task,
// This is the task
comp =>
{
// This is the task completion information
comp.Component<TaskCompletionDetails>(
task => (TaskCompletionDetails)task.CompletionInformation,
compInfo =>
{
compInfo.Map(info => info.Date)
.Column("CompletionDate")
.Nullable();
compInfo.Map(info => info.Notes)
.Column("CompletionNotes")
.Nullable();
compInfo.References<User>(info => info.User)
.Column("CompletedByUserId")
.Nullable()
.Fetch.Join();
});
});
}
These are some other related reading I have followed without success:
Reference:
http://wiki.fluentnhibernate.org/Fluent_mapping
Fluent Nhibernate Many-to-Many mapping with extra column

heres a way which depends on the id generation strategy used. if Identity is used then this won't do (at least NH discourages use of Identity for various reasons), but with every strategy that inserts the id itself it would work:
class JobMap : ClassMap<Job>
{
public JobMap()
{
Id(x => x.Id);
HasMany(x => x.Tasks)
.KeyColumn("JobId");
}
}
class TaskMap : ClassMap<Task>
{
public TaskMap()
{
Table("JobTask");
Id(x => x.Id, "TaskId");
Component(x => x.CompletionInfo, c =>
{
c.Map(x => x.CompletionDate);
c.References(x => x.User, "CompletedByUserId");
});
Join("Task", join =>
{
join.Map(x => x.Name, "Name");
});
}
}

Related

NHibernate: Projecting child entities into parent properties throws an exception

I have the following parent entity Department which contains a collection of child entities Sections
public class Department
{
private Iesi.Collections.Generic.ISet<Section> _sections;
public Department()
{
_sections = new HashedSet<Section>();
}
public virtual Guid Id { get; protected set; }
public virtual string Name { get; set; }
public virtual ICollection<Section> Sections
{
get { return _sections; }
}
public virtual int Version { get; set; }
}
public partial class Section
{
public Section()
{
_employees = new HashedSet<Employee>();
}
public virtual Guid Id { get; protected set; }
public virtual string Name { get; set; }
public virtual Department Department { get; protected set; }
public virtual int Version { get; set; }
}
I would like to transform (flatten) it to the following DTO
public class SectionViewModel
{
public string DepartmentName { get; set; }
public string SectionName { get; set; }
}
Using the following code.
SectionModel sectionModel = null;
Section sections = null;
var result = _session.QueryOver<Department>().Where(d => d.Company.Id == companyId)
.Left.JoinQueryOver(x => x.Sections, () => sections)
.Select(
Projections.ProjectionList()
.Add(Projections.Property<Department>(d => sections.Department.Name).WithAlias(() => sectionModel.DepartmentName))
.Add(Projections.Property<Department>(s => sections.Name).WithAlias(() => sectionModel.SectionName))
)
.TransformUsing(Transformers.AliasToBean<SectionModel>())
.List<SectionModel>();
I am however getting the following exception: could not resolve property: Department.Name of: Domain.Section
I have even tried the following LINQ expression
var result = (from d in _session.Query<Department>()
join s in _session.Query<Section>()
on d.Id equals s.Department.Id into ds
from sm in ds.DefaultIfEmpty()
select new SectionModel
{
DepartmentName = d.Name,
SectionName = sm.Name ?? null
}).ToList();
Mappings
public class DepartmentMap : ClassMapping<Department>
{
public DepartmentMap()
{
Id(x => x.Id, m => m.Generator(Generators.GuidComb));
Property(x => x.Name,
m =>
{
m.Length(100);
m.NotNullable(true);
});
Set(x => x.Sections,
m =>
{
m.Access(Accessor.Field);
m.Inverse(true);
m.BatchSize(20);
m.Key(k => { k.Column("DeptId"); k.NotNullable(true); });
m.Table("Section");
m.Cascade( Cascade.All | Cascade.DeleteOrphans);
},
ce => ce.OneToMany());
}
}
public class SectionMap : ClassMapping<Section>
{
public SectionMap()
{
Id(x => x.Id, m => m.Generator(Generators.GuidComb));
Property(x => x.Name,
m =>
{
m.Length(100);
m.NotNullable(true);
});
ManyToOne(x => x.Department,
m =>
{
m.Column("DeptId");
m.NotNullable(true);
});
}
}
But this throws a method or operation is not implemented.
Seeking guidance on what I am doing wrong or missing.
NHibernate doesn't know how to access a child property's child through the parent entity. A useful thing to remember about QueryOver is that it gets translated directly into SQL. You couldn't write the following SQL:
select [Section].[Department].[Name]
right? Therefore you can't do the same thing in QueryOver. I would create an alias for the Department entity you start on and use that in your projection list:
Department department;
Section sections;
var result = _session.QueryOver<Department>(() => department)
.Where(d => d.Company.Id == companyId)
.Left.JoinQueryOver(x => x.Sections, () => sections)
.Select(
Projections.ProjectionList()
.Add(Projections.Property(() => department.Name).WithAlias(() => sectionModel.DepartmentName))
.Add(Projections.Property(() => sections.Name).WithAlias(() => sectionModel.SectionName))
)
.TransformUsing(Transformers.AliasToBean<SectionModel>())
.List<SectionModel>();
I noticed in your comment you'd like an order by clause. Let me know if you need help with that and I can probably come up with it.
Hope that helps!
This may be now fixed in 3.3.3. Look for
New Feature
[NH-2986] - Add ability to include collections into projections
Not sure but if this is your problem specifically but if you are not using 3.3.3 then upgrade and check it out.
Aslo check out the JIRA
Have you tried a linq query like
from d in Departments
from s in d.Sections
select new SectionModel
{
DepartmentName = d.Name,
SectionName = s == null ? String.Empty : s.Name
}

Basic Fluent NHibernate relationship issue

The project that I am working on at the moment is using Entity Framework, however there are some issues that we have come across and therefore I am researching using NHibernate which we believe will sort out the majority of issues we have.
Anyway, I have been replicating a simple part of the system, but I have ran into what I assume is a very simple problem with a one-to-many relationship as it is giving very strange results.
Here are my entities:
public class Task : Base.Domain
{
private IList<TaskProperty> _taskProperties = new BindingList<taskProperty>();
private string _name = String.Empty;
private string _description = String.Empty;
public virtual IList<TaskProperty> TaskProperties
{
get
{
return _taskProperties;
}
set
{
if (_taskProperties == value) return;
_taskProperties = value;
OnNotifiyPropertyChanged("TaskProperties");
}
}
public virtual string Name
{
get
{
return _name;
}
set
{
if (_name == value) return;
_name = value;
base.OnNotifiyPropertyChanged("Name");
}
}
public virtual string Description
{
get
{
return _description;
}
set
{
if (_description == value) return;
_description = value;
base.OnNotifiyPropertyChanged("Description");
}
}
public Task()
: base()
{ }
}
public class TaskProperty : Base.Domain
{
private Task _task = null;
private string _name = string.Empty;
private string _description = string.Empty;
private int _propertyType = 0;
//public virtual int TaskID { get; set; }
public virtual Task Task
{
get
{
return _task;
}
set
{
if (_task == value) return;
_task = value;
OnNotifiyPropertyChanged("Task");
}
}
public virtual string Name
{
get
{
return _name;
}
set
{
if (_name == value) return;
_name = value;
OnNotifiyPropertyChanged("Name");
}
}
public virtual string Description
{
get
{
return _description;
}
set
{
if (_description == value) return;
_description = value;
OnNotifiyPropertyChanged("Description");
}
}
public virtual int PropertyType
{
get
{
return _propertyType;
}
set
{
if (_propertyType == value) return;
_propertyType = value;
OnNotifiyPropertyChanged("PropertyType");
}
}
public TaskProperty()
: base()
{ }
}
Here are my NHibernate mappings:
public class TaskMapping : ClassMap<Task>
{
public TaskMapping()
{
Id(x => x.Id).Column("RETTaskID");
Map(x => x.Name);
Map(x => x.Description);
Map(x => x.Version);
HasMany(x => x.TaskProperties).KeyColumn("RETTaskPropertyID");
Table("RETTask");
}
}
public class TaskPropertyMapping : ClassMap<TaskProperty>
{
public TaskPropertyMapping()
{
Id(x => x.Id).Column("RETTaskPropertyID");
Map(x => x.Name);
Map(x => x.Description);
Map(x => x.PropertyType);
References(x => x.Task).Column("RETTaskID");
Table("RETTaskProperty");
}
}
Note: The Domain class which these entities inherit from holds the ID (int Id).
The problem that I am facing is that when I get I Task from the database with an ID of 27 for example, I get the TaskProperty with an ID of 27 as well, not the expected 4 TaskProperties that are related to the Task via a foreign key.
This worked fine in Entity Framework and I know this is a simple situation for any ORM, so I assume I have set up my mappings incorrectly, but from all the examples I have found, I don't seem to be doing anything wrong!
Any answers/suggestions will be most welcome. Thanks.
You are almost there. The Column mapping for HasMany and References must be the same:
public TaskMapping()
{
...
HasMany(x => x.TaskProperties).KeyColumn("RETTaskID"); // use this
// HasMany(x => x.TaskProperties).KeyColumn("RETTaskPropertyID"); // instead of this
}
public TaskPropertyMapping()
{
...
References(x => x.Task).Column("RETTaskID");
}
The collection item has to have a reference column to the owner. This column is used for both directions, because that's how the reference in DB managed...

NHibernate one-to-one: null id generated for AccountDetail

I got an exception "null id generated for AccountDetail" when mapping one-to-one relationship by using many-to-one with unique constraint.
Here's my SQL tables:
Account(Id, Name)
AccountDetail(AccountId, Remark)
AccountId is both primary and foreign key.
Here's my Domain Model (Account and AccountDetail):
public class Account
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual AccountDetail Detail { get; set; }
public Account()
{
Detail = new AccountDetail
{
Account = this
};
}
}
public class AccountDetail
{
public virtual int AccountId { get; set; }
public virtual Account Account { get; set; }
public virtual string Remark { get; set; }
}
Mapping (NHibenrate 3.3 mapping by code):
class AccountMap : ClassMapping<Account>
{
public AccountMap()
{
Table(typeof(Account).Name);
Id(c => c.Id, m => m.Generator(Generators.Native));
Property(c => c.Name);
OneToOne(c => c.Detail, m =>
{
m.Constrained(true);
m.Cascade(Cascade.All);
m.PropertyReference(typeof(AccountDetail).GetPropertyOrFieldMatchingName("Account"));
});
}
}
class AccountDetailMap : ClassMapping<AccountDetail>
{
public AccountDetailMap()
{
Table(typeof(AccountDetail).Name);
Id(c => c.AccountId, m =>
{
m.Column("AccountId");
m.Generator(Generators.Foreign<AccountDetail>(x => x.Account));
});
Property(c => c.Remark);
ManyToOne(c => c.Account, m =>
{
m.Column("AccountId");
m.Unique(true);
});
}
}
BTW: Can I remove the AccountId property in AccountDetail? That is, only use the Account property. Using both AccountId and Account properties in AccountDetail class looks not so object-oriented.
Thanks!
I can't say what's actually wrong, but comparing with my working one-to-one relation, I would map it like this:
class AccountMap : ClassMapping<Account>
{
public AccountMap()
{
Table(typeof(Account).Name);
// creates a auto-counter column "id"
Id(c => c.Id, m => m.Generator(Generators.Native));
// doesn't require a column, one-to-one always means to couple primary keys.
OneToOne(c => c.Detail, m =>
{
// don't know if this has any effect
m.Constrained(true);
// cascade should be fine
m.Cascade(Cascade.All);
});
}
}
class AccountDetailMap : ClassMapping<AccountDetail>
{
public AccountDetailMap()
{
Id(c => c.AccountId, m =>
{
// creates an id column called "AccountId" with the value from
// the Account property.
m.Column("AccountId");
m.Generator(Generators.Foreign(x => x.Account));
});
// should be one-to-one because you don't use another foreign-key.
OneToOne(c => c.Account);
}
}

NHibernate.Mapping.ByCode Many-to-Many relations

I've created 2 objects:
public class Set
{
public Set()
{
_sorts = new List<Sort>();
}
public virtual int Id { get; set; }
public virtual string Code { get; set; }
private ICollection<Sort> _sorts;
public virtual ICollection<Sort> Sorts
{
get { return _sorts; }
set { _sorts = value; }
}
}
public class Sort
{
public Sort()
{
_sets = new List<Set>();
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
private ICollection<Set> _sets;
public virtual ICollection<Set> Sets
{
get { return _sets; }
set { _sets = value; }
}
}
And 2 mappings:
public class SetMapping: ClassMapping<Set>
{
public SetMapping()
{
Table("Sets");
Id(x => x.Id, map => map.Generator(IdGeneratorSelector.CreateGenerator()));
Property(x => x.Code, map =>
{
map.Length(50);
map.NotNullable(false);
});
Bag(x => x.Sorts, map =>
{
map.Key(k =>
{
k.Column("SetId");
k.NotNullable(true);
});
map.Cascade(Cascade.All);
map.Table("SetsToSorts");
map.Inverse(true);
}, r => r.ManyToMany(m => m.Column("SortId")));
}
}
public class SortMapping: ClassMapping<Sort>
{
public SortMapping()
{
Table("Sorts");
Id(x => x.Id, map => map.Generator(IdGeneratorSelector.CreateGenerator()));
Property(x => x.Name, map =>
{
map.Length(50);
map.NotNullable(false);
});
}
}
usage:
Set can have many sorts
Sort can belong to many sets.
And I would like to use this as:
var set = new Set() {Code = "001"};
var sort = new Sort {Name = "My name"};
set.Sorts.Add(sort);
sort.Sets.Add(set);
Somehow the relations are not working yet because when I try to use the above code to add sorts to set for example and commit then I don't see any records saved to the SetsToSorts linked table.
Does anyone have a clue what I'm missing in my mapping? Or otherwise doing wrong?
Thank you,
Joost
Your mapping says that Set's Sort collection is inverse (map.Inverse(true)). That means the other side of the bidirectional association is responsible for persisting changes.
But your Sort class mapping doesn't have any collection mapping. Remove map.Inverse(true) on SetMapping or add noninverse collection mapping to SortMapping.

Fluent NHibernate compositeid to mapped class

I'm trying to figure out how to use CompositeId to map another class. Here's a test case:
The tables:
TestParent:
TestParentId (PK)
FavoriteColor
TestChild:
TestParentId (PK)
ChildName (PK)
Age
The classes in C#:
public class TestParent
{
public TestParent()
{
TestChildList = new List<TestChild>();
}
public virtual int TestParentId { get; set; }
public virtual string FavoriteColor { get; set; }
public virtual IList<TestChild> TestChildList { get; set; }
}
public class TestChild
{
public virtual TestParent Parent { get; set; }
public virtual string ChildName { get; set; }
public virtual int Age { get; set; }
public override int GetHashCode()
{
return Parent.GetHashCode() ^ ChildName.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is TestChild)
{
var toCompare = obj as TestChild;
return this.GetHashCode() != toCompare.GetHashCode();
}
return false;
}
}
The Fluent NHibernate maps:
public class TestParentMap : ClassMap<TestParent>
{
public TestParentMap()
{
Table("TestParent");
Id(x => x.TestParentId).Column("TestParentId").GeneratedBy.Native();
Map(x => x.FavoriteColor);
HasMany(x => x.TestChildList).KeyColumn("TestParentId").Inverse().Cascade.None();
}
}
public class TestChildMap : ClassMap<TestChild>
{
public TestChildMap()
{
Table("TestChild");
CompositeId()
.KeyProperty(x => x.ChildName, "ChildName")
.KeyReference(x => x.Parent, "TestParentId");
Map(x => x.Age);
References(x => x.Parent, "TestParentId"); /** breaks insert **/
}
}
When I try to add a new record, I get this error:
System.ArgumentOutOfRangeException :
Index was out of range. Must be
non-negative and less than the size of
the collection. Parameter name: index
I know this error is due to the TestParentId column being mapped in the CompositeId and References calls. However, removing the References call causes another error when querying TestChild based on the TestParentId.
Here's the code that does the queries:
var session = _sessionBuilder.GetSession();
using (var tx = session.BeginTransaction())
{
// create parent
var p = new TestParent() { FavoriteColor = "Red" };
session.Save(p);
// creat child
var c = new TestChild()
{
ChildName = "First child",
Parent = p,
Age = 4
};
session.Save(c); // breaks with References call in TestChildMap
tx.Commit();
}
// breaks without the References call in TestChildMap
var children = _sessionBuilder.GetSession().CreateCriteria<TestChild>()
.CreateAlias("Parent", "p")
.Add(Restrictions.Eq("p.TestParentId", 1))
.List<TestChild>();
Any ideas on how to create a composite key for this scenario?
I found a better solution that will allow querying and inserting. The key is updating the map for TestChild to not insert records. The new map is:
public class TestChildMap : ClassMap<TestChild>
{
public TestChildMap()
{
Table("TestChild");
CompositeId()
.KeyProperty(x => x.ChildName, "ChildName")
.KeyReference(x => x.Parent, "TestParentId");
Map(x => x.Age);
References(x => x.Parent, "TestParentId")
.Not.Insert(); // will avoid "Index was out of range" error on insert
}
}
Any reason you can't modify your query to just be
_sessionBuilder.GetSession().CreateCriteria<TestChild>()
.Add(Restrictions.Eq("Parent.TestParentId", 1))
.List<TestChild>()
Then get rid of the reference?