-1

we are using fluent API and I need to know how I can map it correctly so we can use ParentId instead of having to go through Parent entity. Is that possible? I know it can be done using EF Core so I was hoping for a similar solution.

public class Parent
{
    public int Id {get;set;}
    public ISet<Child> Children {get;set;}
}

public class Child{
    public int Id {get;set;}
    public int ParentId {get;set;}
    public Parent Parent {get;set;}
}

public static void Main()
{
    var dummyQuery = Enumerable.Empty<Child>();
    //Want to do like this.
    dummyQuery= dummyQuery.Where(c => c.ParentId == 80).ToArray();
    
    //This will do a join to the parent table.
    dummyQuery= dummyQuery.Where(c => c.Parent.Id == 80).ToArray();
}

public class ChildMap : ClassMapping<Child>
{
    public ChildMap ()
    {
        Table("Children");


        //how do I do here?
        ManyToOne(x => x.Parent, map => map.Column("ParentId"));


    }
}
Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
XzaR
  • 610
  • 1
  • 7
  • 17
  • I refer to the official docs for the Fluent NHibernate but did not get any information regarding mapping the foreign key in the .net core. I found one [old answer](https://stackoverflow.com/a/42681252/10309381) that could give you some hint. You could try to modify it according to your need may help you in the said issue. – Deepak-MSFT Mar 08 '22 at 06:56
  • @Deepak-MSFT thanks I will look into that. – XzaR Mar 09 '22 at 14:48
  • I consider `public int ParentId {get;set;}` an ugly workaround in EF. – Firo Jun 15 '22 at 11:51
  • Even of its ugly you can get better performance. @Firo as you dont need the extra join that happens with ef. – XzaR Jun 16 '22 at 20:25

1 Answers1

0
public class Parent
{
    public virtual int Id { get; set; }
    public virtual ISet<Child> Children { get; protected set; } = new HashSet<Child>();
}

public class Child
{
    public virtual int Id { get; set; }
    public virtual Parent Parent { get; set; }
}

public class ParentMap : ClassMapping<Parent>
{
    public ParentMap()
    {
        Id(p => p.Id);

        Set(p => p.Children, m => m.Inverse(true), m => m.OneToMany());
    }
}
public class ChildMap : ClassMapping<Child>
{
    public ChildMap()
    {
        Id(c => c.Id);
        
        ManyToOne(c => c.Parent, map => map.Column("ParentId"));
    }
}

// query
var res = session.Query<Child>().Where(c => c.Parent.Id == 80).ToArray();

With this mapping i get the following sql

select child0_.Id as id1_1_, child0_.ParentId as parentid2_1_ from Child child0_ where child0_.ParentId=@p0;@p0 = 80 [Type: Int32 (0:0:0)]

no need for parentId at all. Lazy loading was maybe disabled.

Firo
  • 30,626
  • 4
  • 55
  • 94