我正在使用C#,.NET Framework 4.0和Entity Framework Code First开发WCF RESTful服务。
我有这堂课:
[DataContract]
public class Group
{
[DataMember]
public int GroupId { get; set; }
[DataMember]
public String Name { get; set; }
[DataMember]
public String Description { get; set; }
[DataMember]
public String City { get; set; }
[DataMember]
public String Country { get; set; }
public byte[] Photo { get; set; }
public virtual ICollection<User> Users { get; set; }
}
此课程:
public class User
{
[DataMember]
public int UserId { get; set; }
[DataMember]
public string Name { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
我想使用group
及其所有成员(作为GroupId
的数组)检索UserId
。
现在,我有这句话:
var groups = from g in context.Groups
where g.GroupId == groupId
select g;
但我不知道如何才能获得会员UserId
。
我想获得一个像这样的自定义类:
[DataContract]
public class CustomGroup
{
[DataMember]
public int GroupId { get; set; }
[DataMember]
public String Name { get; set; }
[DataMember]
public String Description { get; set; }
[DataMember]
public String City { get; set; }
[DataMember]
public String Country { get; set; }
[DataMember]
public ICollection<int> UsersIds { get; set; }
}
我该怎么做?
答案 0 :(得分:1)
var result = context.Groups.Where(g=>g.GroupId == groupId)
.Select(e=> new CustomGroup(e));
//With your CustomGroup class should looks like this:
[DataContract]
public class CustomGroup //You should consider some inheritance relationship here
public CustomGroup(Group g){
GroupId = g.GroupId;
Name = g.Name;
Description = g.Description;
City = g.City;
Country = g.Country;
UsersIds = g.Users.Select(u=>u.UserId).ToList();
}
//....
[DataMember]
public ICollection<int> UsersIds { get; set; }
}
答案 1 :(得分:0)
如果我理解你的问题,你会这样做:
var members = context.Groups.Where(group => group.GroupId == groupId).SelectMany(g => g.Users.Select(usr => usr.UserId));