Conditional inclusion () in Entity Framework

I am using EF4.3 with DbContext.

I have an object that I store in the cache, so I will need to load the necessary data before converting to a list and pop it into the cache.

My database is normalized, so the data is spread over several tables. The main object is the "User", the User may or may not be the "Subscriber", and the Subscriber can be one of three types of "Member", "Member" or "Administrator"

Currently, the entire sample is not very elegant due to my lack of knowledge in EF, Linq, etc.

public static User Get(Guid userId) { Guard.ThrowIfDefault(userId, "userId"); var r = new CrudRepo<User>(Local.Items.Uow.Context); var u = r.FindBy(x => x.UserId == userId) .Include("BookmarkedDeals") .Include("BookmarkedStores") .SingleOrDefault(); if (u.IsNotNull() && u.IsActive) { if (u.IsAdmin) { u.GetAdministrator(); } else if (u.IsContributor) { u.GetContributor(); } else if (u.IsMember) { u.GetMember(); } else { string.Format("Case {0} not implemented", u.UserRoleId) .Throw<NotImplementedException>(); } } return u; } 

Each of the Get methods gets a Subscriber object plus the corresponding Include () objects for the role type.

I am sure that this can be done much more elegantly than this, but is struggling with the initial process of thinking.

Anyone help?

UPDATED with an example of one of Get methods

  public static void GetMember(this User user) { Guard.ThrowIfNull(user, "user"); var r = new ReadRepo<Subscriber>(Local.Items.Uow.Context); user.Subscriber = r.FindBy(x => x.UserId == user.UserId) .Include("Kudos") .Include("Member.DrawEntries") .Include("Member.FavouriteCategories") .Include("Member.FavouriteStores") .Single(); } 
+4
source share
2 answers

If your User object is connected to your other objects, you can use the Boot method of the linked collection of objects to get related objects. For example, if your User object has the Subscriber property, you can call u.Subscriber.Load () to get the associated object. The following is an MSDN article

0
source
 var u = r.FindBy(x => x.UserId == userId) .Include("BookmarkedDeals") .Include("BookmarkedStores") .SingleOrDefault(); if(someCondition) { u = u.Include("something"); } 

You have no place to test this, but have you tried this?

0
source

All Articles