我怎样才能回到DbSet<实体GT; AsQueryable已< EntityBase>在MVC4 API控制器? [英] How can I return DbSet<Entity> AsQueryable<EntityBase> in MVC4 api controller?

查看:201
本文介绍了我怎样才能回到DbSet<实体GT; AsQueryable已< EntityBase>在MVC4 API控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC4和实体框架。我想有ApiController叫做UserController中来查询基于属性的用户。
我的用户实体具有像姓名,电话号码,地址(复杂类型)属性,它应该是可能的查询和检索基于该数据的用户。但是,用户也喜欢密码,LASTSYNC等,这些我不想可见性。目前,我没有一个解决方案。下面给我的用户,但所有的实体,也是那些我不想表现。

I am using MVC4 and entity framework. I would like to have ApiController called UserController to query users based on their properties. My User entity has properties like name, phone number, address (complex type) and it should be possible to query and retrieve users based on this data. But user has also properties like password, lastsync, etc. which I do not want to be visible. Currently I don't have a solution. The following gives me the users, but with all the entities, also the ones I don't want to show.

public class UserController : BaseApiController
{
    public IQueryable<User> Get()
    {
        // _db is my entity framework DbContext
        return _db.Users; 
    }
}

我想我应该把所有的公开可见属性ApiUser类,并让用户从ApiUser派生。然后,我的想法是这样做:

I thought I would move all the "publicly" visible properties to ApiUser class and make User derive from ApiUser. Then my idea was to do like this:

public class UserController : BaseApiController
{
    public IQueryable<ApiUser> Get()
    {
        return _db.Users.AsQueryable<ApiUser>(); 
    }
}

这很遗憾不能正常工作,我得到了以下异常:

This unfortunately does not work I get the following exception:

[InvalidOperationException: The type Repository.User was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.]
   Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterDelegatingEnumerable1.Write2_ApiUser(String n, String ns, ApiUser o, Boolean isNullable, Boolean needType) +171
   Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterDelegatingEnumerable1.Write3_ArrayOfApiUser(Object o) +297

你知道我怎么能实现我需要什么?

Do you know how I can achieve what I need?

推荐答案

您可以使用投影:

public IQueryable<ApiUser> Get()
{
    return _db.Users.Select(u => new ApiUser
    {
        Name = u.Name,
        PhoneNumber = u.PhoneNumber,
        Address = u.Address
    });
}

和不获得用户 ApiUser 或其他方式。

And don't derive User from ApiUser or the other way around.

您可以添加然后 - 例如

You can add then - for example - Where extensions to the query:

ApiUser apiUser = Get().Where(au => au.Name == "John Doe").SingleOrDefault();

这篇关于我怎样才能回到DbSet&LT;实体GT; AsQueryable已&LT; EntityBase&GT;在MVC4 API控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆