2014-02-18 35 views
0

嗨,我是新来的实体框架。我有以下对象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; } 

在我的网页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 

任何人都可以告诉我如何实现这一目标?比

回答

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 
           }); 
} 
+0

感谢您的回复。还有一个问题,当我需要使用相同的模型回写数据库时,我将如何去使用该id。谢谢 –

+0

@ J.Davidson您应该创建一个新问题,而不是问更多问题 – Seany84

+0

'HistoryModel'是一个DataTransferObject。您需要从'HistoryModel'构造一个EntityFramework实体并使用它更新数据库。 –

-1

Instade的回报db.lr.AsEnumerable();

试试这个 return db.lr.ToList();

+0

这不是他想要的。他想要回到他自己的类型。 –