How to create a computed (non-mapped) runtime value in Entity Framework root code

I have a user class in EF Code First that contains many properties, and each user has a collection of Contacts, which are other users as a subset of the total number of users. Another "ContactOfOthers" collection is just the flip side, showing who has this user as a contact, as this is a many-to-many relationship.

public class User {

        [Key]
        public string UserName { get; set; }

        // Lots of other properties not relevant to this question...

        [NotMapped]
        public bool IsMyContact { get; set; }

        public virtual ICollection<User> Contacts { get; set; }
        public virtual ICollection<User> ContactOfOthers { get; set; }

}

- ( DB) , IsMyContact. , , , . , "". , , , .

? , , , , , , , ?

+3
2

, IsMyContact User . , ViewModel, User, IsMyContact:

public class UserViewModel
{
    public bool IsMyContact { get; set; }
    public User User { get; set; }
}

( User IsMyContact.)

:

string me = "That me"; // name of the user who is selecting

List<UserViewModel> list = context.Users
   .Where(u => ...some filter...)
   .Select(u => new UserViewModel
          {
              IsMyContact = u.ContactOfOthers.Any(c => c.UserName == me),
              User = u
          })
   .ToList();

: , Contacts, IsMyContactFlag ( , ).

: ViewModel.

+3

, " ", User. linq-to-entities, :

  • linq-to-entity
  • linq-to-entity

, , :

var query = from u in ctx.Users
            where u.Id != id // don't include current user - you can add other condition
            join c in ctx.Users
                         .Where(x => x.Id == id) // current user
                         .SelectMany(x => x.Contacts)
                on u.Id equals c.Id into leftJoin
            from y in leftJoin.DefaultIfEmpty()
            select new 
                {
                    UserName = u.UserName,
                    IsMyContact = y != null
                };

, UserName , . User - :

var users = query.AsEnumerable()
                 .Select(new User
                      {
                          // Project to list in linq-to-objects
                      });
+2

All Articles