且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.net的Web API响应 - 循环数据

更新时间:2023-02-15 17:32:39

这听起来像一个的ViewModels情况。而不是返回你的的消息实体您可以创建一个新的类型,只有你关心的是结果的属性。说你的实体如下:

This sounds like a case for ViewModels. Instead of returning your Message entity you can create a new type with only the properties you care about for that result. Say your entities look like:

public class Message {
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual User User { get; set; }
    public virtual Group Group { get; set; }
}

public class User {
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Message> Messages { get; set; }
}

public class Group {
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Message> Messages { get; set; }
}

和你有一个由组ID检索消息,但不希望有关用户任何信息的端点>或。创建一个视图模型重新present你想要的实际响应:

And you have an endpoint that retrieves a Message by the Group Id but does not want any info about the User or Group. Create a ViewModel to represent the actual response you want:

public class MessageViewModel {
    public int Id { get; set; }
    public string Name { get; set; }
}

和则该实体转换为视图模型:

And then convert the entity to the ViewModel:

public async Task<IHttpActionResult> GetMyMessage(int id)
{
    var messages = await db.Messages.Where(a => a.Group.Id == id).ToListAsync();
    var models = messages.Select(
        m => new MessageViewModel {
            Id = m.Id, 
            Name = m.Name
        }).ToList();

    return Ok(models);
}

现在像返回以下内容:

And now something like the following is returned:

[{id: 1, name: 'SomeMessageName'}, {id: 2, name: 'SomeOtherMessageName'}, ...]