使用HasMany通过自动映射映射相同类型的多个属性

时间:2015-06-05 10:38:16

标签: fluent-nhibernate automapping

我正在尝试在OneToMany关联上映射相同类型的属性。我试图与描述区分,但有点卡在这里。

public class User
{
    public virtual int UserId { get; set; }
    public virtual string UserName { get; set; }

    [Description("From")]
    public virtual IList<Message> FromMessageList { get; set; }

    [Description("To")]
    public virtual IList<Message> ToMessageList { get; set; }   
}

public class Message
{
    public virtual int MessageId { get; set; }
    public virtual string Text { get; set; }

    [Description("From")]
    public virtual User FromUser { get; set; }

    [Description("To")]
    public virtual User ToUser { get; set; }

}

    public class DefaultHasManyConvention : IHasManyConvention
    {
        public void Apply(IOneToManyCollectionInstance instance)
        {
            if (instance.OtherSide.Property.GetDescription() == instance.Member.GetDescription())
            {
                if (instance.Member.GetDescription() != null)
                    instance.Key.Column(instance.Member.GetDescription() + "Id");
                else
                    instance.Key.Column(instance.OtherSide.Property.Name + "Id");

                instance.Fetch.Select();
            }
        }
    }

    public class DefaultReferenceConvention : IReferenceConvention
    {
        public void Apply(IManyToOneInstance instance)
        {
            if (instance.Property.GetDescription() != null)
                instance.Column(instance.Property.GetDescription() + "Id");
            else
                instance.Column(instance.Property.Name + "Id");

            instance.Fetch.Select();
        }
    }

1 个答案:

答案 0 :(得分:1)

对于一对多关系,我通常使用如下编码:

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }

    [Description("From")]
    public virtual ICollection<Message> FromMessageList { get; set; }

    [Description("To")]
    public virtual ICollection<Message> ToMessageList { get; set; }  

}

public class Message
{
    public int MessageId { get; set; }
    public string Text { get; set; }

    [Description("From")]
    public virtual User FromUser { get; set; }
    // From user foreign key column
    [ForeignKey("FromUser")]
    public int FromUserId {get;set;}


    [Description("To")]
    public virtual User ToUser { get; set; }
    // ToUser foreign key column
    [ForeignKey("ToUser")]
    public int ToUserId {get;set;}

}
  1. 尝试使用ICollection代替IList - 这为我解决了很多问题。
  2. 添加外键列名称;它使映射更简单,并且更容易在查询中过滤。