fluent-nhibernate icon indicating copy to clipboard operation
fluent-nhibernate copied to clipboard

Fluent nHibernate map HasMany to Entity/Table with no Primary Key

Open futurechan opened this issue 10 years ago • 0 comments

I am having the worst trouble trying to setup a HasMany relationship to an entity backed by a table with no primary key.

ClassA has a CompositeId. To circumvent the lack of a primary key on ClassB, I tried to create a CompositeId on ClassB that was comprised all of the columns in the table. No matter what I've tried, nothing has worked.

These are my classes and mappings.

    public class ClassA
    {
        public virtual int a_1_id {get;set;}
        public virtual string a_2_id {get;set;}

        public virtual IList<classB> ClassBs { get; set; }

        public override int GetHashCode()
        {
            int hashCode = 0;
            hashCode = hashCode ^ a_1_id ^ a_2_id.GetHashCode();
            return hashCode;
        }

        public override bool Equals(object obj)
        {
            var toCompare = obj as ClassB;

            return (toCompare != null) && (this.GetHashCode() != toCompare.GetHashCode());
        }
    }

    public class ClassAMap : ClassMap<ClassA>
    {
        public ClassAMap()
        {
            Schema("dbo");

            Table("ClassA");

            Not.LazyLoad();

            CompositeId()           
                .KeyProperty(x => x.a_1_id, "a_1_id")
                .KeyProperty(x => x.a_2_id, "a_2_id");      

            HasMany(x => x.ClassBs)
                .Table("ClassB")
                .KeyColumn("a_2_id")
                .Not.LazyLoad();
        }
    }

    public class ClassB
    {
        public virtual string a_2_id {get;set;}
        public virtual string b_field1 {get;set;}

        public override int GetHashCode()
        {
            int hashCode = 0;
            hashCode = hashCode         
                ^ a_2_id.GetHashCode() 
                ^ b_field1.GetHashCode();

            return hashCode;
        }

        public override bool Equals(object obj)
        {
            var toCompare = obj as ClassB;

            return (toCompare != null) && (this.GetHashCode() != toCompare.GetHashCode());
        }
    }

    public class ClassBMap : ClassMap<ClassB>
    {
        public ClassBMap()
        {
            Schema("dbo");

            Table("ClassB");

            Not.LazyLoad();

            CompositeId()           
                .KeyProperty(x => x.a_2_id, "a_2_id")
                .KeyProperty(x => x.b_field1, "b_field1");      
        }
    }

futurechan avatar Aug 08 '14 03:08 futurechan