Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping multiple properties of a same type with HasMany via automapping

I am trying to map properties of the same type on a OneToMany association. I tried to distinguish with Description but kinda stuck here.

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();
        }
    }
like image 509
Mert Avatar asked Jun 05 '15 10:06

Mert


1 Answers

For one to many relationships I generally use coding like :

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. Try to use ICollection instead of IList - this solved many issues for me.
  2. Add foreign key column names; it makes mapping simpler and filtering in queries easier.
like image 55
Bahtiyar Özdere Avatar answered Nov 12 '22 07:11

Bahtiyar Özdere