I have previously asked a question here on SO about a similar topic but have since taken a different approach. This is my model:
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,CustomUserClaim>
{
public ApplicationUser()
{
Friends = new List<Friend>();
}
[Required]
public string Alias { get; set; }
public virtual ICollection<Friend> Friends { get; set; }
}
public class Friend
{
public virtual int Id { get; set; }
public virtual ApplicationUser RequestedBy { get; set; }
public virtual ApplicationUser RequestedTo { get; set; }
public DateTime? RequestTime { get; set; }
public FriendRequestFlag FriendRequestFlag { get; set; }
}
public enum FriendRequestFlag
{
None,
Approved,
Rejected,
Blocked,
Spam
};
I can add Friends with this approach and they populate when I get them from database, sample:
public void AddFriendRequest(ApplicationUser user, ApplicationUser friendUser)
{
var friendRequest = new Friend()
{
RequestedBy = user,
RequestedTo = friendUser,
RequestTime = DateTime.Now,
FriendRequestFlag = FriendRequestFlag.None
};
user.Friends.Add(friendRequest);
}
When I run the code above, the friend table in the database looks like this after execution:
When I get a user I would wan't Entity Framework to get all rows in Friend were the user is either RequestedBy
or RequestedTo
. Is this possible to do with EF? For example with Fluent API? I would also like to map the keys so that [ApplicationUser_Id]
is not needed.
@Mukesh thanks for your answer but I decided to take another approach since your solution did not get all rows in Friend were the user is either RequestedBy or RequestedTo. This is my solution:
Yes you can absolutely do that, just you need to disable lazy loading feature by setting false value to LazyLoadingEnabled,
If you want to fetch friends as well in above scenario then you can get friend list by including navigation property.
To achienve this need to use ForeignKey attribute so that it will not generate [Application_Id] column in table, Please follow below updated model of yours.