2014-02-18 38 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

這不是他想要的。他想要回到他自己的類型。 –