Fluent NHibernate Mapping Error - nhibernate

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

Related

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.

Nhibernate error 'Invalid column name' when column does exist

Hi I have an object called document and one called user
Document
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual User User { get; set; }
Documentmap
public DocumentMap()
{
Map(x => x.Name);
Map(x => x.Description);
References(x => x.User);
}
User
public virtual string UserId { get; set; }
public virtual string FirstName { get; set; }
public virtual string MiddleInitial { get; set; }
public virtual string LastName { get; set; }
private readonly IList<Document> _documents = new List<Document>();
public virtual IEnumerable<Document> Documents { get { return _documents; } }
public virtual void Remove(Document document)
{
_documents.Remove(document);
}
public virtual void Add(Document document)
{
if (!document.IsNew() && _documents.Contains(document)) return;
_documents.Add(document);
}
Map(x => x.UserId);
Map(x => x.FirstName);
Map(x => x.MiddleInitial);
Map(x => x.LastName);
HasMany(x => x.Documents).Access.CamelCaseField(Prefix.Underscore);
Pretty straighforward ( they inherit from base class with stuff like createddate modifieddate etc )
when I try to get all doc by userid I get this
Invalid column name 'UserId'.
the column most definitely is in the table. It also lists several of the base class items as not being there.
I take the sql and past it in query manager and I get intellisense saying they are invalid columns. I run it and it executes just fine. Further more there are plenty of other objects using these base classes with no problems.
I have tried various things like explicitly mapping the key name, the column name using inverse etc to no avail. Don't really know what to do.
Thanks,
Raif
//EDIT as per request sorry it's so verbose. the database is created by nhibernate create schema
Document
public class Document : Entity
{
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual DocumentCategory DocumentCategory { get; set; }
[ValueOf(typeof(DocumentFileType))]
public virtual string FileType { get; set; }
public virtual string FileUrl { get; set; }
public virtual int? Pages { get; set; }
public virtual decimal? Size { get; set; }
public virtual User User { get; set; }
}
public class DocumentMap : EntityMap<Document>
{
public DocumentMap()
{
Map(x => x.Name);
Map(x => x.Description);
Map(x => x.FileUrl);
Map(x => x.Pages);
Map(x => x.Size);
Map(x => x.FileType);
References(x => x.DocumentCategory);
References(x => x.User);
}
}
Entity
public class Entity : IGridEnabledClass, IEquatable<Entity>
{
public virtual int EntityId { get; set; }
public virtual DateTime? CreateDate { get; set; }
public virtual DateTime? ChangeDate { get; set; }
public virtual int ChangedBy { get; set; }
public virtual bool Archived { get; set; }
public virtual bool IsNew()
{
return EntityId == 0;
}
User
public class User : DomainEntity, IUser
{
public virtual string UserId { get; set; }
[ValidateNonEmpty]
public virtual string FirstName { get; set; }
public virtual string MiddleInitial { get; set; }
[ValidateNonEmpty]
public virtual string LastName { get; set; }
public virtual string Title { get; set; }
public virtual DateTime? BirthDate { get; set; }
public virtual string StartPage { get; set; }
public virtual UserLoginInfo UserLoginInfo { get; set; }
public virtual UserStatus UserStatus { get; set; }
public virtual Photo HeadShot { get; set; }
private readonly IList<Document> _documents = new List<Document>();
public virtual IEnumerable<Document> Documents { get { return _documents; } }
public virtual void Remove(Document document)
{
_documents.Remove(document);
}
public virtual void Add(Document document)
{
if (!document.IsNew() && _documents.Contains(document)) return;
_documents.Add(document);
}
several more collections
public class UserMap : DomainEntityMap<User>
{
public UserMap()
{
Map(x => x.UserId);
Map(x => x.FirstName);
Map(x => x.MiddleInitial);
Map(x => x.LastName);
Map(x => x.BirthDate);
Map(x => x.StartPage);
References(x => x.UserStatus);
References(x => x.UserLoginInfo);
References(x => x.HeadShot);
HasMany(x => x.Documents).Access.CamelCaseField(Prefix.Underscore);
database tables create from script select to menu item on management studio
SELECT [EntityId]
,[CreateDate]
,[ChangeDate]
,[ChangedBy]
,[Archived]
,[Name]
,[Description]
,[FileUrl]
,[Pages]
,[Size]
,[FileType]
,[DocumentCategoryId]
,[UserId]
FROM [DecisionCriticalSuite].[dbo].[Document]
GO
SELECT [EntityId]
,[CreateDate]
,[ChangeDate]
,[ChangedBy]
,[Archived]
,[TenantId]
,[OrgId]
,[UserId]
,[FirstName]
,[MiddleInitial]
,[LastName]
,[BirthDate]
,[StartPage]
,[UserStatusId]
,[UserLoginInfoId]
,[HeadShotId]
,[OrganizationId]
FROM [DecisionCriticalSuite].[dbo].[User]
GO
error from nhprof
ERROR:
Invalid column name 'UserId'.
Invalid column name 'UserId'.
Invalid column name 'EntityId'.
Invalid column name 'EntityId'.
Invalid column name 'CreateDate'.
Invalid column name 'ChangeDate'.
Invalid column name 'ChangedBy'.
Invalid column name 'Archived'.
Invalid column name 'FileType'.
Invalid column name 'UserId'.Could not execute query: SELECT documents0_.UserId as UserId1_, documents0_.EntityId as EntityId1_, documents0_.EntityId as EntityId49_0_, documents0_.CreateDate as CreateDate49_0_, documents0_.ChangeDate as ChangeDate49_0_, documents0_.ChangedBy as ChangedBy49_0_, documents0_.Archived as Archived49_0_, documents0_.Name as Name49_0_, documents0_.Description as Descript7_49_0_, documents0_.FileUrl as FileUrl49_0_, documents0_.Pages as Pages49_0_, documents0_.Size as Size49_0_, documents0_.FileType as FileType49_0_, documents0_.DocumentCategoryId as Documen12_49_0_, documents0_.UserId as UserId49_0_ FROM [Document] documents0_ WHERE documents0_.UserId=#p0
Make sure nhibernate is querying against the same database as what you are querying against in sql management studio.
I just had the same issue because I had mapped Entity1.Entity2 as Entity3.
So when joining, it would attempt to use a property from Entity3 as if it existed on Entity2.

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();
}

How to enable LazyLoad in Fluent NHibernate?

I'm testing Fluent NHibernate with NorthWind database. Now, I've created Employee and EmployeeMap class. Source code is like below.
class Employee
public class Employee
{
public virtual int EmployeeID { get; private set; }
public virtual string LastName { get; set; }
public virtual string FirstName { get; set; }
public virtual string Title { get; set; }
public virtual string TitleOfCourtesy { get; set; }
public virtual DateTime? BirthDate { get; set; }
public virtual DateTime? HireDate { get; set; }
public virtual string Address { get; set; }
public virtual string City { get; set; }
public virtual string Region { get; set; }
public virtual string PostalCode { get; set; }
public virtual string Country { get; set; }
public virtual string HomePhone { get; set; }
public virtual string Extension { get; set; }
public virtual string Notes { get; set; }
public virtual Employee ReportsTo { get; set; }
public virtual string PhotoPath { get; set; }
public virtual IList<Territory> Territories{ get; set; }
public Employee()
{
Territories = new List<Territory>();
}
public virtual void AddTerritory(Territory territory)
{
territory.Employees.Add(this);
this.Territories.Add(territory);
}
}
class EmployeeMap
public class EmployeeMap : ClassMap<Employee>
{
public EmployeeMap()
{
Table("Employees");
Id(x => x.EmployeeID);
Map(x => x.LastName);
Map(x => x.FirstName);
Map(x => x.Title);
Map(x => x.TitleOfCourtesy);
Map(x => x.BirthDate);
Map(x => x.HireDate);
Map(x => x.Address);
Map(x => x.City);
Map(x => x.Region);
Map(x => x.PostalCode);
Map(x => x.Country);
Map(x => x.HomePhone);
Map(x => x.Extension);
Map(x => x.Notes);
Map(x => x.PhotoPath);
References(x => x.ReportsTo).Column("ReportsTo").LazyLoad();
HasManyToMany(x => x.Territories)
.Cascade.All()
.Table("EmployeeTerritories")
.ParentKeyColumn("EmployeeID")
.ChildKeyColumn("TerritoryID");
}
}
Then I try to load all employees from database, but all employees have reference object on ReportsTo property.
var sessionFactory = CreateSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (session.BeginTransaction())
{
Console.WriteLine("All employees");
var emp_ = session.CreateCriteria(typeof(Employee));
var employees = emp_.List<Employee>();
foreach (var employee in employees)
{
Console.WriteLine(employee.FirstName); // every employee has reference object on ReportsTo property here.
}
Console.Write("--------");
}
}
I want to know, what wrong with my code and how to fixed it?
Lazy Load is enabled by default. The reference in ReportsTo is a proxy that will only be loaded from the DB if any property other than the ID is used.
Lazy loading is not enabled by default.
public EmployeeMap()
{
Table("Employees");
LazyLoad();
// etc.
}
That being said, testing with a foreach statement can be mischievous, because even if you have enabled lazy loading, the second you query for "employee.FirstName", NHibernate will hit the database and return the results. You're better off catching NHibernate's generated SQL or just using the NHibernate Profiler.

How am I supposed to query for a persisted object's property's subproperty in 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.