2015-12-02 53 views
-1

这是我从中获取我的朋友列表的表格。因为我这个模型如下:如何在MVC中选择Viewmodel

[Key] 
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
public Guid UserRelationshipId { get; set; } 
public string Id { get; set; } 
public string SecondUserId { get; set; } 

// 0 for Request pending 
// 1 for Request Accepted 
// 2 for Declined 
// 3 For Blocked 
public int Status { get; set; } 
public string ActionUserId { get; set; } // who have taken action against the status 

[ForeignKey("Id")] 
public virtual ApplicationUser Users { get; set; } 

现在我使用的查询,我必须让我的朋友列表:

string LoginId = User.Identity.GetUserId(); 
var Searchuser = from u in db.UserRelationships where u.Id == LoginId && u.Status == 1        
       select new UserViewModel 
       { 
        Fname = u.Users.FirstName, 
        Lname = u.Users.LastName, 
        Gender = u.Users.Gender, 
        Id = u.Id, 
        CurrentCity = u.Users.CurrentCity 
       }; 

我得到我自己的数据,因为我比较我的登录ID与身份证。问题是我将如何获取SecondUserId的数据?会有什么疑问?我可以通过使用连接查询来做到这一点,但我想避免它。没有连接查询有没有办法?

+1

请你可以让你的问题更清楚,我很困惑。 – Luke

+0

@Coulton我在模型中提到请检查是否有属性seconduserID这是谁发送给我friendRequest或Vice-versa的身份证。所以你想得到的名单在我的搜索id将是loginuserId –

+0

对不起,我错过了。我仍然不明白的问题虽然:( – Luke

回答

1

您可以通过执行第二查询做到这一点:

string LoginId = User.Identity.GetUserId(); 

// Get the user relationship entity 
var userRelationship = (from u in db.UserRelationships 
         where u.Id == LoginId && u.Status == 1 
         select u).FirstOrDefault(); 

// Get the second user, using the values in the user relationship entity 
var secondUser = db.Users.Find(userRelationship.SecondUserId); 

// Generate the view model 
var viewModel = new UserViewModel() 
       { 
        Fname = userRelationship.Users.FirstName, 
        Lname = userRelationship.Users.LastName, 
        Gender = userRelationship.Users.Gender, 
        Id = userRelationship.Id, 
        CurrentCity = userRelationship.Users.CurrentCity 
       }; 
+0

我得到相同的结果视图模型返回loginuser ID的详细信息ony –