Fluent NHibernate - NHibernate.QueryException: could not resolve property - nhibernate

To start, yes, there are tons of similar questions here on Stack Overflow, but I've browsed them all and the problems that plague most of them look correct on my issue.
Basically, I'm trying to access an Object's Object via my query, and that could be the problem: is that not allowed? I can access the Id field, always, but any other member variable cannot be accessed.
Here are my Objects:
public class Logfiles
{
public virtual int Id { get; set; }
public virtual bool IsActive { get; set; }
public virtual DateTime LastReference { get; set; }
}
public class LogMerges
{
public virtual int Id { get; set; }
public virtual DateTime CreationDate { get; set; }
public virtual Logfiles Logfile { get; set; }
}
And here are my mappings:
class LogfilesMap : ClassMap<Logfiles>
{
public LogfilesMap()
{
Not.LazyLoad();
Table("logfiles");
Id(x => x.Id, "id").Not.Nullable().Unique().GeneratedBy.Identity().UnsavedValue(0);
Map(x => x.IsActive, "is_active").Not.Nullable().Default("true");
Map(x => x.LastReference, "last_reference").Not.Nullable();
}
}
class LogMergesMap : ClassMap<LogMerges>
{
public LogMergesMap()
{
Not.LazyLoad();
Table("logmerges");
Id(x => x.Id, "id").Not.Nullable().Unique().GeneratedBy.Identity().UnsavedValue(0);
Map(x => x.CreationDate, "creation_date").Not.Nullable();
References(x => x.Logfile, "logfile_id");
}
}
My table and columns have the names:
logfiles - id, is_active, last_reference
logmerges - id, creation_date, logfile_id
My code that I'm using to query:
var query = session.QueryOver<LogMerges>()
.Where(log => log.Logfile.IsActive == true);
IEnumerable<LogMerges> logmerges = query.List().OrderBy(c => c.CreationDate);
Performing the Query causes the error and generates:
NHibernate.QueryException: could not resolve property: Logfile.IsActive of: LogMerges
The only thing I can guess is that I'm not allowed to do the "log.Logfile.IsActive" chain of objects in these queries. It compiles just fine and I can't see why I wouldn't be able to do this. If I change it to:
var query = session.QueryOver<LogMerges>()
.Where(log => log.Logfile.Id == 0);
...the query goes through. However, if I try to access the other member variable:
var query = session.QueryOver<LogMerges>()
.Where(log => log.Logfile.LastReference == DateTime.Now);
...I get a similar "could not resolve property" error message.
So if it turns out that I CANNOT do the Object chain of "log.Logfile.IsActive", what's the proper way to implement it? Do I need to perform a bunch of JOINs to do this?
Thanks in advance for any help!

Yes, you do need do need to join on Logfile. Nhibernate is ultimately going to turn your QueryOver query into SQL, so accessing a property on a referenced table doesn't make sense. In other words, you couldn't write the SQL:
select
*
from
logmerges
where
logmerges.logfile.last_reference = ...
Obviously you'd get a syntax error here--you'd need to join to LogFile:
select
*
from
logmerges
inner join logfiles on logfiles.id = logmerges.logfile_id
where
logfiles.last_reference = ...
And so therefore you can't write QueryOver like that either.
var query = session.QueryOver<LogMerges>()
.JoinQueryOver(lm => lm.LogFile)
.Where(lf => lf.LastReference == DateTime.Now)
.List<LogMerges>();

Related

Orchard CMS ISessionConfigurationEvents and 1:N, N:N Relationships?

I have spent many days trying to implement relationships within OrchardCMS 1.9.1 between my custom contentParts to no avail.
Strewn across the internet are many others trying to achieve the same thing, who have also failed; giving me the impression that it's impossible?
Though recently I read an article at: http://www.ideliverable.com/blog/isessionconfigurationevents that gave the impression that all things possible with Fluent Nhibernate should be possible within Orchard.
So I implemented:
public class DbMapping : ISessionConfigurationEvents
{
public void Created(FluentConfiguration cfg, AutoPersistenceModel defaultModel)
{
defaultModel.UseOverridesFromAssemblyOf<ProfilePartRecord>().Alterations(x => x.AddFromAssemblyOf<ProfileOverride>());
defaultModel.UseOverridesFromAssemblyOf<LocationPartRecord>().Alterations(x => x.AddFromAssemblyOf<LocationOverride>());
}
public void Prepared(FluentConfiguration cfg) { }
public void Building(Configuration cfg) { }
public void Finished(Configuration cfg) { }
public void ComputingHash(Hash hash) { }
}
public class LocationOverride : IAutoMappingOverride<LocationPartRecord>
{
public void Override(AutoMapping<LocationPartRecord> mapping)
{
//[ Profile ] <--> [ Location ]
//mapping.Id(x => x.Id, "LocationPartRecord_id"); //As it's not in the model due to being a contentPart, NH will throw an error because of such.
mapping.Map(x => x.Type);
mapping.Map(x => x.Name);
mapping.References(x => x.ProfilePartRecord, "ProfilePartRecord_id");
}
}
public class ProfileOverride : IAutoMappingOverride<ProfilePartRecord>
{
public void Override(AutoMapping<ProfilePartRecord> mapping)
{
//[ Profile ] 0.1 <---> N [ Location ]
//NEW
mapping.HasMany(x => x.Locations)
.Inverse()
//.KeyColumn("ProfilePartRecord_id")
.Cascade.All()
.ForeignKeyCascadeOnDelete()
.ForeignKeyConstraintName("FK_Location__Profile");
}
}
MODELS:
public class ProfilePartRecord : ContentPartRecord
{
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
[CascadeAllDeleteOrphan]
public virtual IList<LocationPartRecord> Locations { get; set; }
public ProfilePartRecord()
{
Locations = new List<LocationPartRecord>();
}
}
public class LocationPartRecord : ContentPartRecord
{
public virtual string Type { get; set; }
public virtual string Name { get; set; }
//For HasMany
[CascadeAllDeleteOrphan]
public virtual ProfilePartRecord ProfilePartRecord { get; set; }
}
MIGRATION:
SchemaBuilder.CreateTable("ProfilePartRecord",
table => table
.ContentPartRecord()
//PK: ProfilePartRecord_id
.Column<string>("FirstName")
.Column<string>("LastName")
//System
.Column<DateTime>("CreatedAt")
);
ContentDefinitionManager.AlterPartDefinition("ProfilePart",
builder => builder.Attachable());
ContentDefinitionManager.AlterTypeDefinition("Profile", t => t
.WithPart(typeof(ProfilePart).Name)
.WithPart("UserPart")
);
ContentDefinitionManager.AlterTypeDefinition("User", t => t
.WithPart("ProfilePart")
);
SchemaBuilder.CreateTable("LocationPartRecord",
table => table
.ContentPartRecord()
//PK: LocationPartRecord_id
//FK:
.Column<int>("ProfilePartRecord_id")
.Column<string>("Type")
.Column<string>("Name")
//System
.Column<DateTime>("CreatedAt")
);
ContentDefinitionManager.AlterPartDefinition("LocationPart",
builder => builder.Attachable());
ContentDefinitionManager.AlterTypeDefinition("Location", type => type
.WithPart("CommonPart")
.WithPart("LocationPart")
.Creatable()
.Listable());
But alas, I still can't create a relationship between these two entities. I can do such via Migration, but this is very limited - as in - I can't set the relationship to Cascade.
Can anyone shed some light on whether this is possible, and if so, how? Thanks
This may not get you the whole way, but I believe it will help. One thing I have done for performance reasons as well as to establish relationships at the database level between my parts is to use the "CreateForeignKey" and "CreateIndex" in the Migration. Here is an example that should work for you
// Add foreign key
SchemaBuilder.CreateForeignKey(
"FK_LocationProfile",
"LocationPartRecord", new[] { "ProfilePartRecord_id" },
"ProfilePartRecord", new[] { "Id" });
// Add index
SchemaBuilder.AlterTable("LocationPartRecord",
table => table
.CreateIndex("IDX_ProfilePartRecord_Id", "ProfilePartRecord_Id")
);
With these relationships defined, I wonder if that will in any way impact the NHibernate work you are doing.
As for how we have done the overall goal I believe you are trying to achieve, you can monitor the "ProfilePart" "Delete" event in the "LocationPart" handler and apply your own cascading delete logic there to ensure that there are no "LocationPart" left around.

Nhibernate query for items that have a Dictionary Property containing value

I need a way to query in Nhibernate for items that have a Dictionary Property containing value.
Assume:
public class Item
{
public virtual IDictionary<int, string> DictionaryProperty {get; set;}
}
and mapping:
public ItemMap()
{
HasMany(x => x.DictionaryProperty)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.AsMap<string>(
index => index.Column("IDNumber").Type<int>(),
element => element.Column("TextField").Type<string>().Length(666)
)
.Cascade.AllDeleteOrphan()
.Fetch.Join();
}
I want to query all Items that have a dictionary value of "SomeText". The following example in Linq fails:
session.Query<Item>().Where(r => r.DictionaryProperty.Any(g => g.Value == "SomeText"))
with error
cannot dereference scalar collection element: Value
So is there any way to achieve that in NHibernate? Linq is not an exclusive requirement but its preffered. Not that I'm not interested to query over dictionary keys that can be achieved using .ContainsKey . Φορ this is similar but not the same
Handling IDictionary<TValueType, TValueType> would usually bring more issues than advantages. One way, workaround, is to introduce a new object (I will call it MyWrapper) with properties Key and Value (just an example naming).
This way we have to 1) create new object (MyWrapper), 2) adjust the mapping and that's it. No other changes... so the original stuff (mapping, properties) will work, because we would use different (readonly) property for querying
public class MyWrapper
{
public virtual int Key { get; set; }
public virtual string Value { get; set; }
}
The Item now has
public class Item
{
// keep the existing for Insert/Updae
public virtual IDictionary<int, string> DictionaryProperty {get; set;}
// map it
private IList<MyWrapper> _properties = new List<MyWrapper>();
// publish it as readonly
public virtual IEnumerable<MyWrapper> Properties
{
get { return new ReadOnlyCollection<MyWrapper>(_properties); }
}
}
Now we will extend the mapping:
HasMany(x => x.Properties)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.Component(c =>
{
c.Map(x => x.Key).Column("IDNumber")
c.Map(x => x.Value).Column("TextField")
})
...
;
And the Query, which will work as expected:
session
.Query<Item>()
.Where(r =>
r.Properties.Any(g => g.Value == "SomeText")
)
NOTE: From my experience, this workaround should not be workaround. It is preferred way. NHibernate supports lot of features, but working with Objects brings more profit

Fluent Nhibernate will not save

I have the following classes:
public class PhoneModel
{
public virtual ModelIdentifier SupportModels
}
public class ModelIdentifier
{
public virtual string Name
public virtual IList<string> Values
}
This is how i mapped it:
mapping.Component(x => x.SuppoertedModel, y =>
{
y.Map(x => x.Name, "FAMILY_ID");
y.HasMany(x => x.Values).Element("VALUE").Table("SUPPORTEDMODULS")
}
2 tables were created:
PhoneModel
column "FAMILY_ID"
SUPPORTEDMODELS
column "VALUE", "PHONE_MODEL_ID"
The problem is that when I am adding values, it will not save it to the SUPPORTEDMODELS table:
var pm = new PhoneModel();
pm.SupportedModels.Name = "11"
pm.SupportedModels.Values.Add("34");
you are missing HasMany(x => x.Values).Cascade.AllDeleteOrphan()
maybe session.Flush() or transaction.Commit() is missing in the test code
btw: if the order of the Values is not important then change it to ICollection<string> and HasMany().AsSet() since this allows NH to optimise some things and code can not rely on the order which is not relyable when using sql.

Fluent Nhibernate - how do i specify table schemas when auto generating tables in SQL CE 4

I am using SQL CE as a database for running local and CI integration tests (normally our site runs on normal SQL server). We are using Fluent Nhibernate for our mapping and having it create our schema from our Mapclasses. There are only two classes with a one to many relationship between them. In our real database we use a non dbo schema. The code would not work with this real database at first until i added schema names to the Table() methods. However doing this broke the unit tests with the error...
System.Data.SqlServerCe.SqlCeException : There was an error parsing the query. [ Token line number = 1,Token line offset = 26,Token in error = User ]
These are the classes and associatad MapClasses (simplified of course)
public class AffiliateApplicationRecord
{
public virtual int Id { get; private set; }
public virtual string CompanyName { get; set; }
public virtual UserRecord KeyContact { get; private set; }
public AffiliateApplicationRecord()
{
DateReceived = DateTime.Now;
}
public virtual void AddKeyContact(UserRecord keyContactUser)
{
keyContactUser.Affilates.Add(this);
KeyContact = keyContactUser;
}
}
public class AffiliateApplicationRecordMap : ClassMap<AffiliateApplicationRecord>
{
public AffiliateApplicationRecordMap()
{
Schema("myschema");
Table("Partner");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.CompanyName, "Name");
References(x => x.KeyContact)
.Cascade.All()
.LazyLoad(Laziness.False)
.Column("UserID");
}
}
public class UserRecord
{
public UserRecord()
{
Affilates = new List<AffiliateApplicationRecord>();
}
public virtual int Id { get; private set; }
public virtual string Forename { get; set; }
public virtual IList<AffiliateApplicationRecord> Affilates { get; set; }
}
public class UserRecordMap : ClassMap<UserRecord>
{
public UserRecordMap()
{
Schema("myschema");
Table("[User]");//Square brackets required as user is a reserved word
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Forename);
HasMany(x => x.Affilates);
}
}
And here is the fluent configuraton i am using ....
public static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(
MsSqlCeConfiguration.Standard
.Dialect<MsSqlCe40Dialect>()
.ConnectionString(ConnectionString)
.DefaultSchema("myschema"))
.Mappings(m => m.FluentMappings.AddFromAssembly(typeof(AffiliateApplicationRecord).Assembly))
.ExposeConfiguration(config => new SchemaExport(config).Create(false, true))
.ExposeConfiguration(x => x.SetProperty("connection.release_mode", "on_close")) //This is included to deal with a SQLCE issue http://stackoverflow.com/questions/2361730/assertionfailure-null-identifier-fluentnh-sqlserverce
.BuildSessionFactory();
}
The documentation on this aspect of fluent is pretty weak so any help would be appreciated
As usual, 10 minutes after posting i answer my own questions. The trick was to not declare the schema in the the ClassMaps. Instead i used the DefaultSchema method in the fluent configuration. So my actual 'live' configuration looks like this :
var configuration = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("connectionStringKey"))
.DefaultSchema("myschema"))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<AffiliateApplicationRecord>());
return configuration;
And my integration tests look like this:
return Fluently.Configure()
.Database(
MsSqlCeConfiguration.Standard
.Dialect<MsSqlCe40Dialect>()
.ConnectionString(ConnectionString))
.Mappings(m => m.FluentMappings.AddFromAssembly(typeof(AffiliateApplicationRecord).Assembly))
.ExposeConfiguration(config => new SchemaExport(config).Create(false, true))
.ExposeConfiguration(x => x.SetProperty("connection.release_mode", "on_close")) //This is included to deal with a SQLCE issue http://stackoverflow.com/questions/2361730/assertionfailure-null-identifier-fluentnh-sqlserverce
.BuildSessionFactory();
Hopefully someone else will get somevalue out of this...
I think this has more to do with SQL Server CE than nhibernate. I am pretty sure that Sql Server CE will not accept schemas at all. its not a supported feature.
See the Create Table Documentation on MSDN

NHibernate 3 LINQ : How to filter IQueryable to select only objects of class T and its subclasses?

I want to upgrade my application to use NHiberante 3 instead of NHibernate 2.1.2 but faced some problems with the new LINQ provider. This question is about one of them. Assume that I have a following hierarchy of classes:
public abstract class PageData
{
public int ID { get; set; }
public string Title { get; set; }
}
public class ArticlePageData : PageData
{
public DateTime PublishedDate { get; set; }
public string Body { get; set; }
}
public class ExtendedArticlePageData : ArticlePageData
{
public string Preamble { get; set; }
}
I use Fluent NHibernate to map these classes to the database:
public class PageDataMap : ClassMap<PageData>
{
public PageDataMap()
{
Table("PageData");
Id(x => x.ID);
Map(x => x.Title);
DiscriminateSubClassesOnColumn("PageType");
}
}
public class ArticlePageDataMap : SubclassMap<ArticlePageData>
{
public ArticlePageDataMap()
{
Join("ArticlePageData", p =>
{
p.KeyColumn("ID");
p.Map(x => x.PublishedDate);
p.Map(x => x.Body);
});
}
}
public class ExtendedArticlePageDataMap : SubclassMap<ExtendedArticlePageData>
{
public ExtendedArticlePageDataMap ()
{
Join("ExtendedArticlePageData", p =>
{
p.KeyColumn("ID");
p.Map(x => x.Preamble);
});
}
}
And then I want to query all pages and do some filtering:
IQueryable<PageData> pages = session.Query<PageData>();
...
var articles = pages.OfType<ArticlePageData>().Where(x => x.PublishedDate >= (DateTime.Now - TimeSpan.FromDays(7))).ToList();
NHibernate 3.0.0 fails with the NotSupported exception in this case, but there is bugfix NH-2375 in the developing version of NH which leads this code to work. But, unfortunately, OfType() method filters the objects by exact type and only selects objects of ArticlePageData class. The old Linq to NH provider selects ArticlePageData and ExtendedArticlePageData in the same case.
How can I do such filtering (select only objects of class T and its subclasses) with the new Linq to NH provider?
session.Query<T>().OfType<SubT>() makes little sense, and it won't let you filter on properties of the subclass. Use session.Query<SubT>() instead.
You can use
var articles = pages.AsEnumerable().OfType<ArticlePageData>().Where(x => x.PublishedDate >= (DateTime.Now - TimeSpan.FromDays(7))).ToList();
and wait for NHibernate 3.0.1.
or maybe you can use
session.Query<ArticlePageData>()
instead of
session.Query<PageData>()