1
\$\begingroup\$

There are some related collection objects in my table and I'm trying to get list with joining this tables. But this code is seems bad:

Entities that shortened:

User:

public partial class User
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public User()
    {
        this.UserVip = new HashSet<UserVip>();
    }
    public int Id { get; set; }
    public int UserID { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<UserVip> UserVip { get; set; }
}

UserVip

public partial class UserVip
{
    public int UserVIPID { get; set; }
    public int UserID { get; set; }
    public int VIPID { get; set; }
    public virtual User User { get; set; }
    public virtual VipType VipType { get; set; }
}

VipType

public partial class VipType
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public VipType()
    {
        this.UserVip = new HashSet<UserVip>();
    }

    public int VIPID { get; set; }
    public string Name { get; set; }
    public short BonusRatio { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<UserVip> UserVip { get; set; }
}

I'm trying to develop that: If user is in uservip table get user's uservip's viptype:

  System.Linq.Expressions.Expression<Func<UserActivity, object>>[] includeExps = new System.Linq.Expressions.Expression<Func<UserActivity, object>>[1] { x => x.User.UserVip.FirstOrDefault() != null ? x.User.UserVip.FirstOrDefault().VipType : null };
  var userActivities = includeExps.Aggregate(context.UserActivity.Where(x => x.ActivityID == activityID && x.OptionID == optionID), (current, exp) => current.Include(exp)).ToList();
\$\endgroup\$
2
  • 2
    \$\begingroup\$ You're spot on about 'this code seems bad.' If no one else answers this in the next couple days I'll try to remember to come back to it and help you out. (Hopefully you get some good reviews in the mean time.) :) \$\endgroup\$ Feb 4, 2017 at 5:51
  • \$\begingroup\$ i'm waiting you @EBrown :) \$\endgroup\$ Feb 4, 2017 at 18:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.