Fluent NHibernate Composite ID table problem

廉价感情. 提交于 2019-12-01 23:44:55
docmanhattan

I've had lots of problems with doing things with composite ids, such as this. I'd suggest doing what I did which is create a new type that just encompasses what the composite id uses for the id and then mapping it like so:

CompositeId<UserToDoId>(x => x.ID)
    .KeyReference(x => x.UserIdPart, c_userID)
    .KeyReference(x => x.AchievementIdPart, c_missionID);

Where UserToDoId has the two references used in the composite id:

public class UserToDoId
{
    User UserIdPart { get; set; }
    Achievement AchievementIdPart { get; set; }

    public override bool Equals(object obj)
    {
        return Equals(obj as UserToDoId);
    }

    private bool Equals(UserToDoId other)
    {
        if (ReferenceEquals(other, null)) return false;
        if (ReferenceEquals(other, this)) return true;

        return UserIdPart.ID == other.UserIdPart.ID &&
            MissionIdPart.ID == other.MissionIdPart.ID;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = GetType().GetHashCode();
            hash = (hash * 31) ^ UserIdPart.ID.GetHashCode();
            hash = (hash * 31) ^ MissionIdPart.ID.GetHashCode();

            return hash;
        }
    }
}

I have no idea why, but there are a bunch of little problems that pop up when you don't use another type to hold the pieces of the component id.

One problem I had was linked at the beginning on my answer. Another one I had was using a composite id for a parent abstract class with subclass mappings would attempt to create instances of the abstract class (which you can't do) for certain queries. Implementing this new type fixed both of these problems.

Give it a try and see if that works. Also, 'achievment' is spelled 'achievement' (not trying to taunt, I just hope you'll avoid people snickering at your code cause of a spelling error :-D)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!