0

我正在使用 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)来检索 a 。

现在,我有这句话:

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; }
}

我怎样才能做到这一点?

4

2 回答 2

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; }
}
于 2013-10-10T14:38:56.173 回答
0

如果我正确理解你的问题,你会这样做:

var members = context.Groups.Where(group => group.GroupId == groupId).SelectMany(g => g.Users.Select(usr => usr.UserId));
于 2013-10-10T14:04:25.590 回答