我正在使用Entity Framework Code First数据层开发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; }
}
ServiceContract 方法:
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.而用户1 Friends
导航属性指向用户2,并继续。
你知道为什么我不退货吗?
答案 0 :(得分:1)
您必须启用代理创建才能支持延迟加载。您可以做的是在查询中使用Include
来加载导航属性。
var users = from u in context.Users.Include(u=>u.Friends)
where u.UserId == userId
select u;
或者另一个解决方案是使用单独的对象模型作为WCF契约(DTO)。然后,您可以启用延迟加载,然后将所有必需的值从EF实体对象(代理)复制到新的数据传输对象。您可以使用Automaper之类的内容轻松映射对象。