简体   繁体   中英

Fluent NHibernate: How to map FK keys as properties in .NET Core version

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"));


    }
}
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM