FluentNHibernate.QueryOver.Join.Where() Could not determine member type from - fluent-nhibernate

I have searched and tried a number of different methods to do this with LINQ/NHibernate and couldn't get anything to work.
I am trying to get the REF fields that have no BolContainer from my data. I keep either getting this error:
"Could not determine member type from bc"
Or getting back all the REF fields, regardless of whether they have a BolContainer or not.
Database
CREATE TABLE dbo.REF (
Id BIGINT PRIMARY KEY IDENTITY(1,1) NOT NULL,
HL_Id BIGINT REFERENCES HL(Id) NOT NULL,
ElementOrder SMALLINT NOT NULL,
Element01 VARCHAR(3) NOT NULL,
Element02 VARCHAR(30) NOT NULL,
Element03 VARCHAR(80) NULL
)
CREATE TABLE dbo.BolContainer (
Id BIGINT PRIMARY KEY IDENTITY(1,1) NOT NULL,
BSN_Id BIGINT UNIQUE REFERENCES BSN(Id) NOT NULL,
REF_Id BIGINT UNIQUE REFERENCES REF(Id) NOT NULL,
ErrorId BIGINT REFERENCES Error(Id) NULL,
Rejected BIT NULL,
Complete BIT NULL,
Deleted BIT NULL
)
Entities
public class REF : EdiEntity
{
public virtual short Order { get; set; }
public virtual string Element01 { get; set; }
public virtual string Element02 { get; set; }
public virtual string Element03 { get; set; }
public virtual HL HL { get; set; }
public virtual BolContainer BolContainer { get; set; }
}
public class BolContainer : Entity
{
public virtual bool? Rejected { get; set; }
public virtual bool? Complete { get; set; }
public virtual bool? Deleted { get; set; }
public virtual BSN BSN { get; set; }
public virtual REF REF { get; set; }
public virtual Error Error { get; set; }
public virtual void AddBSN(BSN bsn)
{
bsn.BolContainer = this;
BSN = bsn;
}
public virtual void AddREF(REF r)
{
r.BolContainer = this;
REF = r;
}
public virtual void AddError(Error error)
{
error.BolContainers.Add(this);
Error = error;
}
}
Mapping
public class REFMap : ClassMap<REF>
{
public REFMap()
{
Id(x => x.Id);
References(x => x.HL, "HL_Id");
Map(x => x.Order, "ElementOrder");
Map(x => x.Element01);
Map(x => x.Element02);
Map(x => x.Element03);
HasOne(x => x.BolContainer)
.Cascade.All()
.Not.LazyLoad()
.Fetch.Join();
}
}
public class BolContainerMap : ClassMap<BolContainer>
{
public BolContainerMap()
{
Id(x => x.Id);
Map(x => x.Rejected).Nullable();
Map(x => x.Complete).Nullable();
Map(x => x.Deleted).Nullable();
References(x => x.BSN, "BSN_Id")
.Cascade.All();
References(x => x.REF, "REF_Id")
.Cascade.All()
.Not.LazyLoad()
.Fetch.Join();
References(x => x.Error, "ErrorId")
.Cascade.All()
.Nullable();
}
}
This is my function with a number of my various unfruitful attempts:
public IList<REF> GetUnprocessedBols()
{
ISession DbSession = SessionFactory.OpenSession();
//var x = from REF r in DbSession.Query<REF>()
// where r.Element01 == "MB" && r.BolContainer != null
// select r;
//return x.ToList<REF>();
//return DbSession.CreateCriteria<REF>()
// .Add(Restrictions.Where<REF>(r => r.Element01 == "MB"))
// //.Add(Restrictions.Where<REF>(r => r.BolContainer == null))
// .List<REF>();
//REF bolAlias = null;
//BolContainer bolContainerAlias = null;
//var result = DbSession
// .QueryOver<REF>(() => bolAlias)
// .Where(r => r.Element01 == "MB")
// .WithSubquery
// .WhereNotExists<BolContainer>(
// QueryOver.Of<BolContainer>(() => bolContainerAlias)
// .Where(() => bolAlias.BolContainer == null)
// .Select(x => x.REF)
// );
//return result.List();
//return DbSession
// .QueryOver<BolContainer>()
// .Right.JoinQueryOver(x => x.REF)
// .Where(r => r.Element01 == "MB")
// .Where(r => r.BolContainer == null)
// .Select(bc => bc.REF)
// .List<REF>();
return DbSession
.QueryOver<REF>()
.Where(r => r.Element01 == "MB")
.Left.JoinQueryOver(x => x.BolContainer)
.Where(bc => bc == null)
.List();
}
I'd like to get the bottom most one working, but will settle for any of them.
I'd rather not resort to HQL, or filtering the List afterwards, but I'm not sure if I can get it working otherwise.
Thanks for the help,
Jeff

After stubbornly playing around with the different methods I tried I finally got one to work.
REF bolAlias = null;
BolContainer bolContainerAlias = null;
var result = DbSession
.QueryOver<REF>(() => bolAlias)
.Where(r => r.Element01 == "MB")
.WithSubquery
.WhereNotExists<BolContainer>(
QueryOver.Of<BolContainer>(() => bolContainerAlias)
.Where(() => bolAlias.Id == bolContainerAlias.REF.Id)
.Select(x => x.REF)
);
return result.List();
It doesn't answer the "Could not determine member type from" question, but it does fix the problem. Maybe the answer can help someone or provide an example at least.

Related

NHibernate - Error dehydrating property value - updating entity

I'm having problem when saving an entity with association. Below is my code which gives the error
Fluent Class inherited from Fluent Migration
public override void Up() //Update your changes to the database
{
Create.Table("assinatura")
.WithColumn("id").AsInt32().Identity().PrimaryKey()
.WithColumn("usuario_id").AsInt32()
.WithColumn("isfreeplan").AsInt32() //1 sim 0 nao
.WithColumn("gratuito_datafinal").AsDateTime()
Create.Table("usuarios")
.WithColumn("id").AsInt32().Identity().PrimaryKey()
.WithColumn("nomecompleto").AsString(256) //Patricia dos Santos
.WithColumn("email").AsString(512) //patricia#gmail.com
.WithColumn("password").AsString(128) //123123123
Create.ForeignKey("IX_FK_AssinaturasUsuarios")
.FromTable("assinatura").ForeignColumn("usuario_id")
.ToTable("usuarios").PrimaryColumn("id");
}
Mapping of Table "Usuario"
public class UsuariosMap : ClassMapping<Usuario>
{
public enum Niveis { CADASTRADO = 0, REQUISITOU_PAGAMENTO = 1 }
public virtual int id { get; set; }
public virtual string nomecompleto { get; set; }
public virtual string email { get; set; }
public virtual string password { get; set; }
public UsuariosMap()
{
Table("usuarios");
Id(x => x.id, x => x.Generator(Generators.Identity));
Property(x => x.nomecompleto, x => x.NotNullable(true));
Property(x => x.email, x => x.NotNullable(true));
Property(x => x.password, x => x.NotNullable(true));
Bag(x => x.assinaturas, map => {
map.Table("assinatura");
map.Lazy(CollectionLazy.Lazy);
map.Inverse(true);
map.Key(k => k.Column(col => col.Name("usuario_id")));
map.Cascade(Cascade.All); //set cascade strategy
}, rel => rel.OneToMany());
}
Mapping of Table "Assinatura"
public class Assinatura
{
public virtual int Id { get; set; }
public virtual int usuario_id { get; set; }
public virtual int isfreeplan { get; set; }
public virtual DateTime gratuito_datafinal { get; set; }
public virtual Usuario usuario { get; set; }
}
public class AssinaturaMap : ClassMapping<Assinatura>
{
public AssinaturaMap()
{
Table("assinatura");
Id(x => x.Id, x => x.Generator(Generators.Identity));
Property(x => x.usuario_id, x => x.NotNullable(true));
Property(x => x.isfreeplan, x => x.NotNullable(true));
Property(x => x.gratuito_datafinal, x => x.NotNullable(true));
ManyToOne(x => x.usuario, x=>
{
x.Cascade(Cascade.DeleteOrphans);
x.Column("usuario_id");
x.ForeignKey("IX_FK_AssinaturasUsuarios");
});
}
}
When I try to update a User "Usuario" adding a new "Assinatura" I am getting an error
var user = Database.Session.Load<Usuario>(1);
var ass = new Assinatura
{
isfreeplan = 0,
gratuito_datafinal = DateTime.Now,
usuario = user
};
if (user != null)
{
user.assinaturas.Add(ass);
Database.Session.SaveOrUpdate(user);
}
An exception of type 'NHibernate.PropertyValueException' occurred in NHibernate.dll but was not handled in user code
{"Error dehydrating property value for Test.Models.Assinatura.usuario"}
Inner Exc: {"Parameter index is out of range."}
Property Name: usuario
I just want to do a basic one-to-many relationship between Usuario table and Assinature table (1 user has one or many assinaturas).
The exception:
Parameter index is out of range
is telling us, that we are working with one DB column twice. And that is because of this doubled mapping:
Property(x => x.usuario_id, x => x.NotNullable(true));
ManyToOne(x => x.usuario, x=>
{
x.Cascade(Cascade.DeleteOrphans);
x.Column("usuario_id");
...
It is ok to use one column for more properties (one value type, one reference).. but only for reading (loading values from DB)
For insert / update... we can use only one of these. And always is better to keep read/write reference, and property readonly
Property(x => x.usuario_id, x => {
x.NotNullable(true)
x.Insert(false)
x.Update(false)
})

NHibernate - Invalid index for this SqlParameterCollection with Count (Mapping By Code)

I am having a real problem with NHibernate Mapping By Code and a Composite Key in one of my classes.
The Domain class is as follows:-
public partial class UserRole {
public virtual int UserId { get; set; }
public virtual int RoleId { get; set; }
//public virtual UserRoleId Id { get; set; }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
[NotNullNotEmpty]
public virtual DateTime VqsCreateDate { get; set; }
public virtual DateTime? VqsUpdateDate { get; set; }
[NotNullNotEmpty]
public virtual bool VqsMarkedForDelete { get; set; }
[Length(50)]
public virtual string VqsCreateUserName { get; set; }
[Length(50)]
public virtual string VqsLastUpdatedUserName { get; set; }
[NotNullNotEmpty]
[Length(128)]
public virtual string VqsCreateSessionId { get; set; }
[Length(128)]
public virtual string VqsLastUpdatedSessionId { get; set; }
[NotNullNotEmpty]
[Length(15)]
public virtual string VqsCreateIpAddress { get; set; }
[Length(15)]
public virtual string VqsLastUpdatedIpAddress { get; set; }
[Length(255)]
public virtual string VqsCreateSessionInfo { get; set; }
[Length(255)]
public virtual string VqsLastUpdatedSessionInfo { get; set; }
[NotNullNotEmpty]
public virtual bool VqsAllowDelete { get; set; }
public virtual bool? VqsAllowEdit { get; set; }
[Length(50)]
public virtual string VqsRffu1 { get; set; }
[Length(50)]
public virtual string VqsRffu2 { get; set; }
[Length(50)]
public virtual string VqsRffu3 { get; set; }
#region NHibernate Composite Key Requirements
public override bool Equals(object obj) {
if (obj == null) return false;
var t = obj as UserRole;
if (t == null) return false;
if (UserId == t.UserId
&& RoleId == t.RoleId)
return true;
return false;
}
public override int GetHashCode() {
int hash = GetType().GetHashCode();
hash = (hash * 397) ^ UserId.GetHashCode();
hash = (hash * 397) ^ RoleId.GetHashCode();
return hash;
}
#endregion
}
And the mapping class is as follows:-
public partial class UserRoleMap : ClassMapping<UserRole> {
public UserRoleMap() {
Schema("Membership");
Lazy(true);
ComposedId(compId =>
{
compId.Property(x => x.UserId, m => m.Column("UserId"));
compId.Property(x => x.RoleId, m => m.Column("RoleId"));
});
Property(x => x.VqsCreateDate, map => map.NotNullable(true));
Property(x => x.VqsUpdateDate);
Property(x => x.VqsMarkedForDelete, map => map.NotNullable(true));
Property(x => x.VqsCreateUserName, map => map.Length(50));
Property(x => x.VqsLastUpdatedUserName, map => map.Length(50));
Property(x => x.VqsCreateSessionId, map => { map.NotNullable(true); map.Length(128); });
Property(x => x.VqsLastUpdatedSessionId, map => map.Length(128));
Property(x => x.VqsCreateIpAddress, map => { map.NotNullable(true); map.Length(15); });
Property(x => x.VqsLastUpdatedIpAddress, map => map.Length(15));
Property(x => x.VqsCreateSessionInfo, map => map.Length(255));
Property(x => x.VqsLastUpdatedSessionInfo, map => map.Length(255));
Property(x => x.VqsAllowDelete, map => map.NotNullable(true));
Property(x => x.VqsAllowEdit);
Property(x => x.VqsRffu1, map => map.Length(50));
Property(x => x.VqsRffu2, map => map.Length(50));
Property(x => x.VqsRffu3, map => map.Length(50));
ManyToOne(x => x.User, map =>
{
map.Column("UserId");
////map.PropertyRef("Id");
map.Cascade(Cascade.None);
});
ManyToOne(x => x.Role, map =>
{
map.Column("RoleId");
////map.PropertyRef("Id");
map.Cascade(Cascade.None);
});
}
}
Whenever I try to insert into this table I get the following error:-
Invalid index for this SqlParameterCollection with Count 'N'
I have looked at all the occurrences of this error on StackExchange and across the majority of the internet for the last day and am still no further on.
There seem to be a lot of examples for Xml and Fluent mapping, but very little for Mapping By Code.
I think I have tried every combination of suggestions, but all to no avail.
I am fully aware that the problem is related to the fact that I have the ID fields in the table referenced twice and this is ultimately causing the error,
The problem is that I need both the ID and Entity Fields in my class as they are used extensively throughout the code.
I seem to be experiencing the issue as I have the combination of a composite and foreign keys in my many to many table.
Any help that anyone could provide to preserve my sanity would be very much appreciated.
Many thanks in advance.
Simon
You can set Insert(false) and Update(false) to prevent Nhibernate from generating an update or insert statement which includes the User and Role columns (which do not exist).
ManyToOne(x => x.User, map =>
{
map.Column("UserId");
////map.PropertyRef("Id");
map.Cascade(Cascade.None);
map.Insert(false);
map.Update(false);
});
ManyToOne(x => x.Role, map =>
{
map.Column("RoleId");
////map.PropertyRef("Id");
map.Cascade(Cascade.None);
map.Insert(false);
map.Update(false);
});
That's the same as Not.Update() Not.Insert() in Fluent mapping.
If you now create a valid UserRole object and set bot IDs to valid user/role ID NHibernate should be able to persist your object.

Fluent NHibernate One to Many - Transient Instance Exception

I am attempting to do a simple one to many mapping in fluent NHibernate, however i receive the following exception:
"NHibernate.TransientObjectException : object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave. Type: Voter.Domain.Entities.VoteOption, Entity: Voter.Domain.Entities.VoteOption"
I have tried numerous using Cascade().All() - but this makes no difference.
Please help me to get this cascade working! Much time already wasted...
I have the following entities:
public class Vote
{
public Vote()
{
VoteOptions = new List<VoteOption>();
}
public virtual int Id { get; protected set; }
public virtual Guid VoteReference { get; set; }
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual DateTime ValidFrom { get; set; }
public virtual DateTime ValidTo { get; set; }
public virtual IList<VoteOption> VoteOptions { get; set; }
public virtual void AddOption(VoteOption voteOption)
{
VoteOptions.Add(voteOption);
}
public virtual void AddOptions(List<VoteOption> options)
{
foreach (var option in options.Where(option => VoteOptionAlreadyExists(option) == false))
{
VoteOptions.Add(option);
}
}
private bool VoteOptionAlreadyExists(VoteOption voteOption)
{
return VoteOptions.Any(x => x.Description == voteOption.Description);
}
}
public class VoteOption
{
public virtual int Id { get; protected set; }
public virtual string LongDescription { get; set; }
public virtual string Description { get; set; }
public virtual Vote Vote { get; set; }
}
And the following mappings:
public VoteMap()
{
Table("Vote");
Id(x => x.Id).GeneratedBy.Identity().Column("Id");
Map(x => x.VoteReference).Column("VoteReference");
Map(x => x.Title).Column("Title").Not.Nullable();
Map(x => x.Description).Column("Description").Not.Nullable();
Map(x => x.ValidFrom).Column("ValidFrom").Not.Nullable();
Map(x => x.ValidTo).Column("ValidTo").Not.Nullable();
HasMany(x => x.VoteOptions).KeyColumn("Vote_Id").Cascade.All();
}
public class VoteOptionMap : ClassMap<VoteOption>
{
public VoteOptionMap()
{
Table("VoteOption");
Id(x => x.Id).GeneratedBy.Identity().Column("Id");
Map(x => x.Description).Column("Description").Not.Nullable();
Map(x => x.LongDescription).Column("LongDescription").Not.Nullable();
References(x => x.Vote).Column("Vote_Id").Cascade.All();
}
}
And the following SQL Server database tables:
CREATE TABLE dbo.Vote
(
Id INT IDENTITY(1,1) PRIMARY KEY,
VoteReference UNIQUEIDENTIFIER NULL,
Title VARCHAR(500) NOT NULL,
[Description] VARCHAR(1000) NOT NULL,
ValidFrom DATETIME NOT NULL,
ValidTo DATETIME NOT NULL
)
CREATE TABLE dbo.VoteOption
(
Id INT IDENTITY(1,1) PRIMARY KEY,
Vote_Id INT NOT NULL,
[Description] VARCHAR(500) NOT NULL,
LongDescription VARCHAR(5000) NOT NULL
)
Implementation code is:
public void Save()
{
var vote = new Vote
{
VoteReference = new Guid(),
Title = "Events Vote",
Description = "Which event would you like to see next?",
ValidFrom = DateTime.Now.AddDays(-2),
ValidTo = DateTime.Now.AddDays(3)
};
var options = new List<VoteOption>
{
new VoteOption {Description = "What you want?", LongDescription = "Tell me all about it..."},
new VoteOption {Description = "Another option?", LongDescription = "Tell me some more..."}
};
vote.AddOptions(options);
using (var session = sessionFactory().OpenSession())
{
using (var transaction = session.BeginTransaction())
{
//This works - but undermines cascade!
//foreach (var voteOption in vote.VoteOptions)
//{
// session.Save(voteOption);
//}
session.Save(vote);
transaction.Commit();
}
}
}
private ISessionFactory sessionFactory()
{
var config = new Configuration().Configure();
return Fluently.Configure(config)
.Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Vote>()))
.BuildSessionFactory();
}
I would say, that setting as shown above (the fluent mapping) is ok. Other words, the code I see right now, seems to be having different issue, then the Exception at the top.
The HasMany cascade setting is OK, but I would suggest to mark it as inverse (see here for more info ... NHibernate will not try to insert or update the properties defined by this join...)
HasMany(x => x.VoteOptions)
.KeyColumn("Vote_Id")
.Inverse()
.Cascade.All();
Also, the Reference should be in most case without Cascade: References(x => x.Vote).Column("Vote_Id");
Having this, and running your code we should be recieving at the moment the SqlException: *Cannot insert the value NULL into column 'Vote_Id'*
Because of the TABLE dbo.VoteOption defintion:
...
Vote_Id INT NOT NULL, // must be filled even on a first INSERT
So, the most important change should be in the place, where we add the voteOption into Vote collection (VoteOptions). We always should/must be providing the reference back, ie. voteOption.Vote = this;
public virtual void AddOption(VoteOption voteOption)
{
VoteOptions.Add(voteOption);
voteOption.Vote = this; // here we should/MUST reference back
}
public virtual void AddOptions(List<VoteOption> options)
{
foreach (var option in options.Where(option => VoteOptionAlreadyExists(option) == false))
{
VoteOptions.Add(option);
option.Vote = this; // here we should/MUST reference back
}
}
After these adjustments, it should be working ok
The cascade option can be set globally using Fluent NHibernate Automapping conventions. The issue that #Radim Köhler pointed out also needs to be corrected when adding items to the List.
Using global conventions:
Add a convention, it can be system wide, or more restricted.
DefaultCascade.All()
Code example:
var cfg = new StoreConfiguration();
var sessionFactory = Fluently.Configure()
.Database(/* database config */)
.Mappings(m =>
m.AutoMappings.Add(
AutoMap.AssemblyOf<Product>(cfg)
.Conventions.Setup(c =>
{
c.Add(DefaultCascade.All());
}
)
.BuildSessionFactory();
Now it will automap the cascade when saving.
More info
Wiki for Automapping
Table.Is(x => x.EntityType.Name + "Table")
PrimaryKey.Name.Is(x => "ID")
AutoImport.Never()
DefaultAccess.Field()
DefaultCascade.All()
DefaultLazy.Always()
DynamicInsert.AlwaysTrue()
DynamicUpdate.AlwaysTrue()
OptimisticLock.Is(x => x.Dirty())
Cache.Is(x => x.AsReadOnly())
ForeignKey.EndsWith("ID")
See more about Fluent NHibernate automapping conventions

How to get records in first table(projects) not present in second table(finances) with foreign key reference using nhibernate

I'm trying to query on a simple data structure in nhibernate and MSSQL
dbo.Projects : Id(int, not null)
dbo.Finances : Id(int, not null), ProjectId(int,not null), foreign key references to dbo.projects
I want to get all the records in projects table that are not present in finances table where the finances table has a foreign key reference ProjectId.
I am migrating to (Fluent) Nhibernate 3 from EntityFramework?
//So far I have got here:
public IQueryable<ProjectModel> GetProjectsNotPresentInFinance()
{
var factory = Fluently.Configure()
.Database(MsSqlConfiguration
.MsSql2008
.ConnectionString(m_connectionString))
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<ProjectMap>()
).BuildSessionFactory();
using (var session = factory.OpenSession())
{
var allprojects = session.QueryOver<ProjectModel>();
var projectsToReturn = allprojects.List<ProjectModel>().AsQueryable();
//--- Something like : all the records not in finances table ---------
// .Where( proj => !db.Finances.Where(fin => fin.ProjectId == proj.Id).Any())
// .Select(project => new ProjectModel
// {
// Id=project.Id,
// ProjectName = project.ProjectName,
// });
return projectsToReturn;
}
}
public class FinanceModel
{
public virtual int Id { get; set; }
public virtual int ProjectId { get; set; }
}
public class ProjectModel
{
public virtual int Id { get; set; }
public virtual string ProjectName { get; set; }
}
public class ProjectMap:ClassMap<ProjectModel>
{
public ProjectMap() {
Table("Projects");
Id(x => x.Id);
Map(x => x.ProjectName);
}
}
public class FinanceMap : ClassMap<FinanceModel>
{
public FinanceMap()
{
Table("Finances");
Id(x => x.Id);
References(x => x.ProjectModel);
}
}
//-------------------------------------------------------
//This is an Equivalent working code Using EntityFramework :
public IQueryable<ProjectModel> GetProjectsNotPresentInFinance() {
IQueryable<ProjectModel> projectList = db.Projects
.Where( proj => !db.Finances.Where(fin => fin.ProjectId == proj.Id).Any())
.Select(project => new ProjectModel
{
Id=project.Id,
ProjectName = project.ProjectName,
});
return projectList;
}
//-------------------------------------------------------
On second thought, you may try this without changing anything to your mapping, using a subquery :
var notOrphanProjectIdsSubquery = QueryOver.Of<FinanceModel>()
.Select(x => x.ProjectId);
var orphanProjects = session.QueryOver<ProjectModel>()
.WithSubquery
.WhereProperty(x=>x.Id)
.NotIn(notOrphanProjectIdsSubquery)
.List();
----------------------- Initial answer
Assuming you have a mapped Finances Property in your Project class, and according to https://stackoverflow.com/a/14980450/1236044, it should be something like :
var orphanProjects = session.QueryOver<ProjectModel>()
.WhereRestrictionOn(x => x.Finances).IsEmpty()
.List();
I must confess I am not proficient with FluentNH. I guess the classes and mappings should be something like this, hoping I'm not setting you on the wrong track...
public class FinanceModel
{
public virtual int Id { get; set; }
public virtual int ProjectId { get; set; }
public virtual ProjectModel Project{get;set;}
}
public class ProjectModel
{
public virtual int Id { get; set; }
public virtual string ProjectName { get; set; }
public virtual IList<FinanceModel> Finances { get; set; }
}
public class ProjectMap:ClassMap<ProjectModel>
{
public ProjectMap() {
Table("Projects");
Id(x => x.Id);
Map(x => x.ProjectName);
HasMany(x => x.Finances);
}
}
public class FinanceMap : ClassMap<FinanceModel>
{
public FinanceMap()
{
Table("Finances");
Id(x => x.Id);
References(x => x.Project);
}
}

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?