0

I have the following entities

Item
virtual public int serialNumber { get; set; }
virtual public Project idProject { get; set; }
virtual public string type{ get; set; }

Project
virtual public int idProject { get; set; }
virtual public string projectName { get; set; }
virtual public int numDovelas { get; set; }
virtual public IList<Item> lItems{ get; set; }

Both classes are mapped and they work just fine, but my question is about how can I get with one query a Project element with the lItems already filled with the items that are of that project

UPDATE (after Niyaz answer)

I have added a third entity to the model which represents the type of Analysis for an Item, and an item can have several Analysis performed on different dates and save on different files. So the mapping of that third entity is as follows

Table("Analysis");
CompositeId()
    .KeyReference(x => x.SerialNumber, "serialNumber") // Reference to the Item entity
    .KeyProperty(x => x.MeasureDate, "measureDate")
    .KeyProperty(x => x.FileName, "fileName");
Map(x => x.Measure1).Column("measure1").Not.Nullable().Default("0");
Map(x => x.Measure2).Column("measure2").Not.Nullable().Default("0");

And I've added to the Item mapping the following

HasMany(x=>x.LAnalysis).KeyColumn("serialNumber") 

To add the type of the relationship and the column that is the FK

But now I have the following error

Foreign key (FK9CF1483E7BAABE07:Analysis [SerialNumber])) must have same number of columns as the referenced primary key (Item [SerialNumber, ProjectID])

So it appears that the Analysis table must have as well the ProjectID, there is no way to avoid that? Or something that can be done to avoid this error

a.ras2002
  • 385
  • 2
  • 7
  • 21

1 Answers1

0

1) You need to add reference to Project in Item mapping (if you are using FluentNhibernate) like this:

public class ItemMap: ClassMap<Item>
    {
        public ItemMap()
        {
            Id(x => x.serialNumber);
            References(x => x.Project, "idProject");//you need to change your property to actual entity, not just Id
            Map(x => x.type);
            Table("NameOfTable");
        }
    }

2) And you need to indicate that Project has many Items in Project mapping

    HasMany(x => x.lItems).KeyColumn("serialNumber");

I think it should work. If not, you need to use LINQ to get the list of Items of particular Project and assign them to that object

  • Thanks Niyaz, I will try that. So in every case that I have a FK I need to add the References and the HasMany as well (or the type of relation that is) – a.ras2002 Apr 12 '18 at 06:22
  • Try to reference the items like in this question (rebelliard's answer) https://stackoverflow.com/questions/3691366/fluent-nhibernate-how-to-map-a-foreign-key-column-in-the-mapping-class – Niyaz Mukhamedya Apr 12 '18 at 15:16