How am I supposed to query for a persisted object's property's subproperty in nhibernate? - nhibernate

I'm feeling dumb.
public class Uber
{
public Foo Foo { get; set; }
public Bar Bar { get; set; }
}
public class Foo
{
public string Name { get; set; }
}
...
var ubercharged = session.CreateCriteria(typeof(Uber))
.Add(Expression.Eq("Foo.Name", "somename"))
.UniqueResult<Uber>();
return ubercharged;
This throws a "could not resolve property" error.
What am I doing wrong? I want to query for an Uber object that has a property Foo which has a Name of "somename".
updated with real life example, repository call, using fluent nhibernate:
public UserPersonalization GetUserPersonalization(string username)
{
ISession session = _sessionSource.GetSession();
var personuser = session.CreateCriteria(typeof(UserPersonalization))
.Add(Expression.Eq("User.Username", username))
.UniqueResult<UserPersonalization>();
return personuser;
}
The classes/mappings:
public class User
{
public virtual Guid UserId { get; set; }
public virtual string Username { get; set; }
public virtual string Email { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string PasswordSalt { get; set; }
public virtual bool IsLockedOut { get; set; }
public virtual bool IsApproved { get; set; }
}
public class Person
{
public virtual int PersonId { get; set; }
public virtual string Name { get; set; }
public virtual Company Company { get; set; }
}
public class UserPersonalization
{
public virtual int UserPersonalizationId { get; set; }
public virtual Person Person { get; set; }
public virtual User User { get; set; }
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(x => x.UserId).GeneratedBy.Guid().ColumnName("UserId");
Map(x => x.Username);
Map(x => x.PasswordHash);
Map(x => x.PasswordSalt);
Map(x => x.Email);
Map(x => x.IsApproved);
Map(x => x.IsLockedOut);
}
}
public class UserPersonalizationMap : ClassMap<UserPersonalization>
{
public UserPersonalizationMap()
{
WithTable("UserPersonalization");
Id(x => x.UserPersonalizationId).ColumnName("UserPersonalizationId");
References(x => x.Person).ColumnName("PersonId");
References(x => x.User).ColumnName("UserId");
}
}
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Id(x => x.PersonId).ColumnName("PersonId");
Map(x => x.Name);
References(x => x.Company).ColumnName("CompanyId");
}
}

Try this:
var ubercharged = session.CreateCriteria(typeof(Uber))
.CreateCriteria("Foo")
.Add(Restrictions.Eq("Name", "somename"))
.UniqueResult<Uber>();

Can you sort using "ubercharged.AddOrder(Order.asc("Foo.Name")) syntax? This syntax should work in NHib 2.01. If not, your maps are not working correctly.
Stuart's answer should work fine for you though.

Related

Many to Many Nhibernate - Duplicate records and no insert

I have three tables in a many to many relationship with the nhibernate maps below. My objects are also below. A portfolio item can have many tags. The problem I am having is
1) update save another tag even when the name is the same as last time. So duplicate records get inserted into tag when the tag is the same. So for example if the tag for one portfolio object was abc the next portfolio item that adds the tag should reference this record rather than reinserting abc. I think this is because of the id column in the tag map. Nhibernate needs an id though.
2) Create does not add records in the join table. Records in the join table are only added on updates.
Domain Objects
public class Portfolio {
public Portfolio() {
PortfolioImage = new List<Portfolioimage>();
Tag = new List<Tag>();
}
public virtual int PortfolioId { get; set; }
public virtual string AliasTitle { get; set; }
public virtual string MetaDescription { get; set; }
public virtual string Title { get; set; }
public virtual string Client { get; set; }
public virtual string Summary { get; set; }
public virtual string Url { get; set; }
public virtual string MainImage { get; set; }
public virtual string TitleAlt { get; set; }
public virtual string Description { get; set; }
public virtual IList<Portfolioimage> PortfolioImage { get; set; }
public virtual IList<Tag> Tag { get; set; }
}
public class Portfoliotag {
public virtual int Id { get; set; }
public virtual Portfolio Portfolio { get; set; }
public virtual Tag Tag { get; set; }
}
public class Tag {
public Tag() {
Portfolio = new List<Portfolio>();
}
public virtual int TagId { get; set; }
public virtual string TagVal { get; set; }
public virtual IList<Portfolio> Portfolio { get; set; }
}
Maps
public class PortfolioMap : ClassMap<Portfolio> {
public PortfolioMap() {
Table("Portfolio");
LazyLoad();
Id(x => x.PortfolioId).GeneratedBy.Identity().Column("PortfolioId");
Map(x => x.AliasTitle).Column("AliasTitle").Not.Nullable();
Map(x => x.MetaDescription).Column("MetaDescription").Not.Nullable();
Map(x => x.Title).Column("Title").Not.Nullable();
Map(x => x.Client).Column("Client").Not.Nullable();
Map(x => x.Summary).Column("Summary").Not.Nullable();
Map(x => x.Url).Column("Url");
Map(x => x.MainImage).Column("MainImage");
Map(x => x.TitleAlt).Column("TitleAlt");
Map(x => x.Description).Column("Description").Not.Nullable();
HasMany(x => x.PortfolioImage).KeyColumn("PortfolioId").Inverse();
HasManyToMany(x => x.Tag).Table("PortfolioTag").ParentKeyColumn("PortfolioId").ChildKeyColumn("TagId").LazyLoad().Cascade.All().Fetch.Join();
}
}
public class PortfoliotagMap : ClassMap<Portfoliotag> {
public PortfoliotagMap() {
Table("PortfolioTag");
LazyLoad();
Id(x => x.Id).GeneratedBy.Identity().Column("Id");
References(x => x.Portfolio).Not.Nullable().Cascade.SaveUpdate().Column("PortfolioId");
References(x => x.Tag).Not.Nullable().Cascade.SaveUpdate().Column("TagId");
}
}
public class TagMap : ClassMap<Tag> {
public TagMap() {
Table("Tag");
LazyLoad();
Id(x => x.TagId).GeneratedBy.Identity().Column("TagId");
Map(x => x.TagVal).Column("Tag").Not.Nullable();
//HasMany(x => x.PortfolioTag).KeyColumn("TagId");
// HasMany(x => x.PortfolioTag).Cascade.AllDeleteOrphan().Inverse().Fetch.Join().KeyColumn("TagId");
HasManyToMany(x => x.Portfolio).Table("PortfolioTag").ParentKeyColumn("PortfolioId").ChildKeyColumn("TagId").LazyLoad().Inverse().Cascade.AllDeleteOrphan();
}
}
given the classes
public class Portfolio
{
public Portfolio()
{
Tag = new List<Tag>();
}
public virtual int PortfolioId { get; protected set; }
public virtual IList<Tag> Tag { get; protected set; }
}
public class Tag
{
public virtual int TagId { get; set; }
public virtual string Name { get; set; }
}
the this mapping should suffice
public class PortfolioMap : ClassMap<Portfolio>
{
public PortfolioMap()
{
Id(x => x.PortfolioId).GeneratedBy.Identity().Column("PortfolioId");
HasManyToMany(x => x.Tag)
.Table("PortfolioTag")
.ParentKeyColumn("PortfolioId")
.ChildKeyColumn("TagId")
.Cascade.All()
.Fetch.Join();
}
}
assigning existing tags has to be handled in code which can cache or query involved tags more efficiently than automatic querying by any framework.
Update:
example usage which works for me
public void Save(int portfolioId, IEnumerable<string> tagnames)
{
using (var tx = session.BeginTransaction())
{
var tags = Session.QueryOver<Tag>().WhereProperty(x => x.Name).In(tagnames).List();
var portfolio = session.Get<Portfolio>(portfolioId);
portfolio.Tags.Clear();
portfolio.Tags.AddRange(tags);
tx.Commit();
}
}

FluentNhibernate .CheckReference is failing

public class WorldEntity
{
public WorldEntity()
{
Scenes = new List<SceneEntity>();
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Picture { get; set; }
public virtual IList<SceneEntity> Scenes { get; set; }
}
public class WorldMap : ClassMap<WorldEntity>
{
public WorldMap()
{
Table("Worlds");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Name);
Map(x => x.Picture);
HasMany(x => x.Scenes).KeyColumn("Id");
}
}
public class SceneEntity
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual string Image { get; set; }
//public virtual int WorldId { get; set; }
public virtual WorldEntity World { get; set; }
public virtual short NoExits { get; set; }
public virtual string AnimatedIntroPath { get; set; }
}
public class SceneMap: ClassMap<SceneEntity>
{
public SceneMap()
{
Table("Scenes");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Name);
Map(x => x.Image);
Map(x => x.NoExits);
Map(x => x.AnimatedIntroPath);
//Map(x => x.WorldId).Not.Nullable();
References(wrd => wrd.World, "WorldId");
}
}
[Test]
new PersistenceSpecification<SceneEntity>(Session)
.CheckProperty(x => x.Name, "Scene Name")
.CheckProperty(x => x.Image, "path to image")
//.CheckProperty(x=>x.WorldId,aa.Id)
.CheckReference(x => x.World,aa )
.VerifyTheMappings();
after running the test I am getting this error:
System.ApplicationException : For property 'World' expected same element, but got different element of type 'TwitQuestNet.DataDefinitions.OrmConfig.Entities.WorldEntity'.
Tip: override ToString() on the type to find out the difference.
at FluentNHibernate.Testing.Values.Property2.CheckValue(Object target)
at System.Collections.Generic.List1.ForEach(Action1 action)
at FluentNHibernate.Testing.PersistenceSpecification1.VerifyTheMappings(T first)
at TwitQuestNet.Test.EntityMapTests.SceneTest.scene_map_succsess() in SceneTest.cs: line 23
what I am doing wrong here ? as I am stuck for nearly a day :(
Sorted. I had to add EqualityComparer() the the test will pass

two class reference eachother , how to do Not.LazyLoad in fluent nhibernate

i have two class
public class ProInfo
{
public ProInfo()
{
ProPrices = new List<ProPrice>();
}
public virtual Guid ProID { get; set; }
public virtual string ProCate { get; set; }
public virtual string Name { get; set; }
public virtual string Unit { get; set; }
public virtual string PicName { get; set; }
public virtual string Memo { get; set; }
public virtual bool DeleteFlag { get; set; }
public virtual DateTime LastUpDateTime { get; set; }
public virtual IList<ProPrice> ProPrices { get; set; }
}
public class ProPrice
{
public virtual int Id { get; set; }
public virtual AreaInfo AreaInfo { get; set; }
public virtual ProInfo ProInfo { get; set; }
public virtual Decimal Price { get; set; }
}
mapping codes are :
public ProInfoMap()
{
Id(x => x.ProID);
Map(x => x.DeleteFlag);
Map(x => x.Name);
Map(x => x.PicName);
Map(x => x.ProCate);
Map(x => x.Unit);
Map(x => x.LastUpDateTime);
HasMany<ProPrice>(x => x.ProPrices);
}
public ProPriceMap()
{
Id(x => x.Id);
Map(x => x.Price);
References<ProInfo> (x => x.ProInfo);
References<AreaInfo>(x => x.AreaInfo);
}
what i want is to disable the proprices's lazyload(), so i can get all the prices for the product from database. but, when i change the onetomany to this: HasMany<ProPrice>(x => x.ProPrices).Not.LazyLoad(), it cause an Infinite loop. what do i miss?
I don't know, where exactly the loop comes from, but your bidirectional association may cause this. You should declare one side as Inverse(). This can only be done in ProInfoMap, because it is a one-to-many relationship with a bidirectional association:
HasMany<ProPrice>(x => x.ProPrices).Inverse().Not.LazyLoad();
Try that. It may remove the infinite loop.

Illegal access to loading collection in Fluent and Nhibernate

I'm not able to understand why the problem is occurring. Please let me know if there are any errors, I am very new to this topic.
public class Department
{
public virtual int Dept_id { get; set; }
public virtual String Dept_name { get; set; }
public virtual IList<Student> Students { get; set; }
//public virtual ICollection<Student> Students { get; set; }
public Department()
{
Students = new List<Student>();
}
}
public class Student
{
public Student()
{
}
//private int _Dept_id;
//public virtual Guid StudentId { get; set; }
public virtual Guid StudentId { get; set; }
/*public virtual int Dept_id
{
get { return this._Dept_id; }
set { this._Dept_id = value; }
}*/
public virtual int Dept_id { get; set; }
public virtual String Name { get; set; }
public virtual int Age { get; set; }
public virtual String Address { get; set; }
public virtual Department Department { get; set; }
}
public class DepartmentMap : ClassMap<Department>
{
public DepartmentMap()
{
Table("Department");
Id(x => x.Dept_id).Column("Dept_id");
Map(x => x.Dept_name).Column("Dept_name");
HasMany(x => x.Students).KeyColumn("Student_id").Inverse()
.Cascade.All();
}
}
public class StudentMap :ClassMap<Student>
{
public StudentMap()
{
Table("Student");
Id(x => x.StudentId).Column("Student_id").GeneratedBy.GuidComb();
Map(x => x.Name);
Map(x => x.Age);
Map(x => x.Address);
References(x => x.Department).Column("Dept_id")
.Not.Nullable().Not.LazyLoad();
}
}
Now when I am trying this code
[WebMethod(EnableSession = true)]
public List<Student> Students()
{
IList<Student> student = new List<Student>();
ISession session = NHibernateHelper.OpenSession();
student = session.Query<Student>().ToList();
return student.ToList();
}
it gives error in loading the students list inside the department as
illegal access to loading collection
What is lacking in this code and why this is happening?
sorry my bad !! there are cetain changes i made which made it working .. though not sure of apparent shortcomings of the mentioned idea below
changed student class as :
public class Student
{
public Student()
{
}
public virtual Guid StudentId { get; set; }
public virtual int Dept_id
{
get { return Department.Dept_id; }
set { this.Dept_id = Department.Dept_id; }
}
public virtual String Name { get; set; }
public virtual int Age { get; set; }
public virtual String Address { get; set; }
public virtual Department Department { get; set; }
}
and student mapping for the reference as
References(x => x.Department).Column("Dept_id").Cascade.All();
Note : there should be no single Dept Id mapping
and changed the DepartmentMap as :
public DepartmentMap()
{
Table("Department");
Id(x => x.Dept_id).Column("Dept_id");
Map(x => x.Dept_name).Column("Dept_name");
HasMany(x => x.Students).KeyColumn("Dept_id").AsBag();
}

Fluent NHibernate Mapping Error

I am getting the following error using Fluent:
12:16:47,879 ERROR [ 7]
Configuration [(null)]- An association
from the table Address refers to an
unmapped class: System.Int32
NHibernate.MappingException: An
association from the table Address
refers to an unmapped class:
System.Int32
public class Address {
public Address() {
}
public virtual int AddressId {
get;
set;
}
public virtual string AddressLine1 {
get;
set;
}
public virtual string AddressLine2 {
get;
set;
}
public virtual string AddressLine3 {
get;
set;
}
public virtual string BuildingNumber {
get;
set;
}
public virtual string City {
get;
set;
}
public virtual string County {
get;
set;
}
public virtual System.DateTime MovedIn {
get;
set;
}
public virtual System.DateTime MovedOut {
get;
set;
}
public virtual int PersonId {
get;
set;
}
public virtual string PostCode {
get;
set;
}
}
public class AddressMap : ClassMap<Address> {
public AddressMap() {
Table("Address");
LazyLoad();
Id(x => x.AddressId).GeneratedBy.HiLo("1000");
Map(x => x.AddressLine1).Length(100).Not.Nullable();
Map(x => x.AddressLine2).Length(100).Not.Nullable();
Map(x => x.AddressLine3).Length(100).Not.Nullable();
Map(x => x.BuildingNumber).Length(250).Not.Nullable();
Map(x => x.City).Length(250).Not.Nullable();
Map(x => x.County).Length(250).Not.Nullable();
Map(x => x.MovedIn).Not.Nullable();
Map(x => x.MovedOut).Not.Nullable();
References(x => x.PersonId).Column("PersonId").Not.Nullable();
Map(x => x.PostCode).Length(15).Not.Nullable();
}
}
[TestFixture]
public class TestBase
{
protected SessionSource SessionSource { get; set; }
protected ISession Session { get; private set; }
[SetUp]
public void SetupContext()
{
var cfg = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(
"Data Source=localhost;Initial Catalog=ted;User ID=sa;Password=xxxx;"));
SessionSource = new SessionSource(cfg.BuildConfiguration()//**Error Here**
.Properties, new TestModel());
Session = SessionSource.CreateSession();
SessionSource.BuildSchema(Session);
}
[TearDown]
public void TearDownContext()
{
Session.Close();
Session.Dispose();
}
}
I get an error on my initial configuration, I have been over it a few times and I am really unsure what exactly I am doing wrong? Can anyone see anything Obvious? I can confirm there is only 2 int's in the database for this table. AddressId - Non identity PK and PersonId non identity FK
You should have a Person property of type Person, not an id.
Suggested read: https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started