我有这些数据:用户
UserId Name
42 Abc
43 Pqr
44 lmn
45 xyz
映射:
MappingId User1 User2
1 42 43
2 42 44
3 43 44
现在我有1个网络服务,我每秒都会触发以获得用户和用户连接并以这种格式返回json数据:
var data =
[{
"UserId": 42,
"Name": "Abc",
"Connections": [43,44]
}, {
"UserId": 43,
"Name": "Pqr",
"Connections": [44]
}, {
"UserId": 44,
"Name": "Lmn",
"Connections": []
}, {
"UserId": 45,
"Name": "xyz",
"Connections": []
}];
基本上,此Web服务的目的是始终获取新用户和现有用户的新连接,这就是我解雇此问题的原因 每秒都有网络服务。
所以我的条件是这样的(跳过已经获取用户并在那里获取新用户)或(跳过已经获取连接并获取新的 现有用户的连接)但json数据结构应该相同。
因此,在每个Web服务调用上,我获得所有新用户,或者如果新用户不在那里,则获取已建立新连接的现有用户。
使用案例1 :
UserId Name
42 Abc
43 Pqr
输出json :
var data =
[{
"UserId": 42,
"Name": "Abc",
"Connections":[]
},
{
"UserId": 43,
"Name": "xyz",
"Connections":[]
}];
用例2 : 如果在用户42和用户43之间建立连接,则: 输出json :
var data =
[{
"UserId": 42,
"Name": "Abc",
"Connections":[43]
}];
用例3 :新用户输入:
UserId Name
42 Abc
43 Pqr
44 lmn
输出json :
var data =
[{
"UserId": 44,
"Name": "Almn",
"Connections":[]
}];
用例4 :用户42和44之间建立的连接:
var data =
[{
"UserId": 42,
"Name": "Abc",
"Connections":[42,44]
}];
这是我的代码:
public HttpResponseMessage GetUsers([FromUri]Int32 skip = 0)
{
var userBll = new UserBLL();
var result = context.Users.ToList();
var lists = new List<string>();
var connectionsData = context.Mappings.ToList().OrderBy(t => t.CreatedDate.Value.Date).ThenBy(t => t.CreatedDate.Value.TimeOfDay).Skip(skip).Take(1);
lists.Add(connectionsData.FirstOrDefault().User1 + "," + connectionsData.FirstOrDefault().User2);
var response = Request.CreateResponse(HttpStatusCode.OK, result.Select(r => new
{
UserId=r.UserId,
Name = r.FirstName + " " + r.LastName,
Connections = lists
}));
return response;
}
但是使用以下输入数据低于输出:
UserId Name
42 Abc
43 Pqr
44 lmn
45 xyz
MappingId User1 User2
1 42 43
var data =
[{
"UserId": 42,
"Name": "Abc",
"Connections": [42,43]
}, {
"UserId": 43,
"Name": "Pqr",
"Connections": [42,43]
}, {
"UserId": 44,
"Name": "Lmn",
"Connections": [42,43]
}, {
"UserId": 45,
"Name": "xyz",
"Connections": [42,43]
}];
Javascript代码:
var userList = [];
function GetData() {
$.getJSON('Url', {skip:userList.length} ,function (response) {
updateUserList(response);
});
}
function updateUserList(data) {
if (JSON.stringify(userList).toString() != JSON.stringify(data).toString()) { //if old data is not same as new data
userList = data;
}
else
{
setTimeout(GetData, 1000); //fire request every 1 seconds
}
}
注意:我没有外键关系。
答案 0 :(得分:1)
假设Connections
的类型为IEnumerable<int>
;
context.Users.Select(r => new
{
UserId =r.UserId,
Name = r.FirstName + " " + r.LastName,
Connections = context.Mappings.OrderBy(t => t.CreatedDate.Value).Skip(skip).Where(m => m.User1 == r.UserId).Select(m => m.User2)
.Concat(context.Mappings.OrderBy(t => t.CreatedDate.Value).Skip(skip).Where(m => m.User2 == r.UserId).Select(m => m.User1))
});