我正在使用实体框架代码优先数据层开发 WCF REST 服务,并且我有一个导航属性。
用户等级:
[DataContract]
public class User
{
[DataMember]
public int UserId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string City { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string InterestIn { get; set; }
[DataMember]
public virtual ICollection<User> Friends { get; set; }
[DataMember]
public virtual ICollection<User> FromWhomIsFriend { get; set; }
}
服务合约方法:
public List<User> GetUserFriends(string user_id)
{
int userId;
OutgoingWebResponseContext ctx =
WebOperationContext.Current.OutgoingResponse;
if ((user_id == null) ||
(!Int32.TryParse(user_id, out userId)) ||
(userId < 1))
{
ctx.StatusCode = System.Net.HttpStatusCode.BadRequest;
ctx.StatusDescription = "user_id parameter is not valid";
throw new ArgumentException("GetUserFriends: user_id parameter is not valid", "user_id");
}
List<User> friends = null;
try
{
using (var context = new AdnLineContext())
{
context.Configuration.ProxyCreationEnabled = false;
context.Configuration.LazyLoadingEnabled = false;
var users = from u in context.Users.Include("Friends")
where u.UserId == userId
select u;
if ((users != null) &&
(users.Count() > 0))
{
User user = users.First();
//friends = user.Friends.ToList();
friends = new List<User>();
foreach (User f in user.Friends)
{
User us = new User()
{
UserId = f.UserId,
Name = f.Name,
Age = f.Age,
City = f.City,
Country = f.Country,
Email = f.Email,
InterestIn = f.InterestIn,
Friends = f.Friends,
FromWhomIsFriend = f.FromWhomIsFriend
};
friends.Add(us);
}
}
ctx.StatusCode = System.Net.HttpStatusCode.OK;
}
}
catch (Exception ex)
{
ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError;
ctx.StatusDescription = ex.Message;
ctx.SuppressEntityBody = true;
}
return friends;
}
此方法不返回任何内容。如果我评论这一行FromWhomIsFriend = f.FromWhomIsFriend
,它会起作用。
FromWhomIsFriend
是我是他朋友的用户的导航属性。为了表示用户关系,我有这张表:
UserID | FriendID
---------+----------
3 | 1
---------+----------
1 | 2
如果我询问用户 1 的朋友,我得到用户 2,它FromWhomIsFriend
指向用户 1。用户 1Friends
导航属性指向用户 2,然后继续。
你知道我为什么不退货吗?