[英]Can I generate a service reference automatically for a REST WCF service?
[英]WCF REST service doesn't return anything because I have a circular reference (I think)
我正在使用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 = f.FromWhomIsFriend
它可以正常工作。
FromWhomIsFriend
是我作為他的朋友的用戶的導航屬性。 為了表示用戶關系,我有此表:
UserID | FriendID
---------+----------
3 | 1
---------+----------
1 | 2
如果我詢問用戶1的朋友,則得到用戶2,它的FromWhomIsFriend
指向用戶1。用戶1 Friends
導航屬性指向用戶2,然后繼續。
你知道我為什么不退貨嗎?
您必須啟用代理創建才能支持延遲加載。 您可以做的是在查詢中使用“ Include
來加載導航屬性。
var users = from u in context.Users.Include(u=>u.Friends)
where u.UserId == userId
select u;
否則,其他解決方案將使用單獨的對象模型作為WCF合同(DTO)。 然后,您可以啟用延遲加載,然后將EF實體對象(代理)中的所有必需值復制到新的數據傳輸對象。 您可以使用Automaper之類的工具輕松映射對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.