如何从Web Api返回IQueryable DTO让我可以使用Odata过滤器

时间:2012-08-01 14:14:06

标签: entity-framework-4 asp.net-mvc-4 asp.net-web-api odata odp.net

我正在尝试在Web api项目ASP.NET MVC 4.0 RC中使用带有ODP.net和实体框架的Odata过滤器。我想返回一个IQueryable of OwnDTO。我收到内部500错误,没有任何细节。我知道webapi RC存在错误生成错误,但我不认为错误是我的问题。

    Get http://localhost:51744/api/Owner  called using Fiddler




    [Queryable]
    public IQueryable<OwnDTO> Get()        
    {            
        using (Entities context = new Entities())
        {
            var query = from item in context.Owners
                        select
                        new OwnDTO
                        {
                            Name = item.Name

                        };
            return query.AsQueryable();
        }
    }

//非常简单,例如

 public class OwnDTO
    {
        public string Name;
    }

我不想使用我的Oracle EF生成的类(DAO)从我的Get返回,但我知道如果我用更友好的界面替换EntityObject我可以。如果我返回IEnumerable它可以工作,但我想要Odata过滤器。


更新,因为有人想要一个有效的例子..应该在linq中使用自动映射器或者simliar,并且应该注入上下文。


    [Queryable]
    public IQueryable<OwnDTO> Get()        
    {            
        {
            var query = from item in Hack._EFContext.Owners
                        select
                        new OwnDTO
                        {
                            Name = item.Name

                        };
            return query.AsQueryable();
        }
    }

这样做很好,但看起来Odata在RC后被移除了。所以我需要寻找另一条道路。

1 个答案:

答案 0 :(得分:1)

它在RC 中有效,但在出货时可能不在RTM中 - 还不是很清楚。

您的问题是,由于您使用的是using块,因此您正在处置上下文。因此,在检索数据之前,上下文会被释放。

因此,而不是using在请求结束时注册您的对象以进行处置。 Tugberk有一个帖子here

相关问题