具有Web Api返回对象的实体框架

时间:2014-02-18 10:50:48

标签: c# entity-framework asp.net-web-api

您好我是实体框架的新手。我有以下对象

 public partial class lr
    {
        public lr()
        {
            this.lr_history = new HashSet<lr_history>();
            this.people = new HashSet<person>();
        }

        public int _id { get; set; }
        public string name { get; set; }
        public string notes { get; set; }

        public virtual ICollection<lr_history> lr_history { get; set; }
        public virtual ICollection<person> people { get; set; }

在我的Web Api控制器中,我有以下代码

 public class lrController : ApiController
{
    private CTM db = new CTM();

    // GET api/addL
    public IEnumerable<lr> Getlr()
    {
        from a in DbContext.Activities 
        return db.lr.AsEnumerable();
    }

在上面的Get方法中,它返回lr,但我想返回我自己的对象,如

   lr.id
   lr.name
   lr_history.description
   lrh_history.rate

谁能告诉我如何实现这一目标?比

2 个答案:

答案 0 :(得分:1)

创建新模型:

class HistoryModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string HistoryDescription { get; set; }
    public string HistoryRate { get; set; }
}

并返回:

public IEnumerable<HistoryModel> Getlr()
{
    from a in DbContext.Activities 
    return db.lr.AsEnumerable()
                .Select(x => new HistoryModel 
                                 { 
                                     Id = x.id,
                                     Name = x.name,
                                     HistoryDescription = x.history.description,
                                     HistoryRate = x.history.rate
                                 });
}

答案 1 :(得分:-1)

而不是返回db.lr.AsEnumerable();

尝试此返回db.lr.ToList();