9

I am getting exception NHibernate.QueryException : could not resolve property: InsuredId. I am new to NHibernate and I could not figure it out.

Defining Properties

public virtual int InsuredId { get; set; }
public virtual string Gender { get; set; }
public virtual DateTime DateOfBirth { get; set; }
public virtual string SrId { get; set; }
public virtual string SchoolId { get; set; }
public virtual string Ssn { get; set; }
public virtual DateTime GradDate { get; set; }

Mapping data to properties

public InsuredMap()
{
     ReadOnly();

     Table("Insured");
     Id(x => x.Id, "InsuredId");
     Map(x => x.Gender, "SexCd");
     Map(x => x.DateOfBirth, "BirthDt");
     Map(x => x.SrId, "SIDIdNum");
     Map(x => x.SchoolId, "SchoolIdTxt");
     Map(x => x.Ssn, "SocSecNumTxt");
     Map(x => x.GradDate, "GradMthYrNum");
}

Function to fetch all values

public Entities.Insured GetByInsuredId(int insuredId)
{
    var query = Session.QueryOver<Entities.Insured>()
        .Where(x => x.InsuredId == insuredId)
        .Cacheable()
        .CacheRegion(Constants.EntityCacheRegion);

    return query.SingleOrDefault();
}

Unit Test to test the data

[Test]
public void InsuredMapTest()
{
    var insured = repository.GetByInsuredId(714619800);
    Assert.That(insured.Gender, Is.EqualTo("F"));
}  
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
JuniorDev
  • 193
  • 1
  • 2
  • 13

1 Answers1

11

Let me be more precise, and extend the Andrew Whitaker comment.

In the mapping you are saying:

Id(x => x.Id, "InsuredId");

Which is information: My entity/class Insured has

Id(            // an identificator, the key
x => x.Id      // represented by the property **Id** (here is the issue)
, "InsuredId") // its DB representation is the column "InsuredId"

Other words, the C# property

public virtual int InsuredId { get; set; }

is not mapped, with the above statement, so it cannot be used for querying

What we can do in the query, to make it working is

var query = Session.QueryOver<Entities.Insured>()
    //.Where(x => x.InsuredId == insuredId)
    .Where(x => x.Id == insuredId)
    ...

And the could not resolve property: InsuredId exception will disappear, because we are using the mapped property Id

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Which leads to the question, can you have a calculated field using Fluent Nhibernate? – Jess Oct 06 '14 at 18:13
  • Not fully sure, what are you searching for, but could [this](http://stackoverflow.com/a/13966856/1679310) help? We do have `formula=""` attribute in NHibernate... – Radim Köhler Oct 06 '14 at 18:20
  • More like this: http://stackoverflow.com/questions/2386981/fluent-nhibernate-and-computed-properties – Jess Oct 06 '14 at 18:21