0

我在 ASP.Net WebApi 项目中有以下控制器。该模型是使用实体框架生成的。

 public class CategoriesController : ApiController
    {
        private eLearningDbEntities context = new eLearningDbEntities();


        // GET api/Categories
        public IEnumerable<Categories> GetCategories()
        {
            var query = from c in context.Categories
                        select c;
            return query;
        }
    }

从浏览器调用控制器时,我得到以下结果,但我只想获取模型的属性,而不是所有上下文属性。有什么想法有什么问题吗?

<ArrayOfCategories xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/eLearning.DomainModel">
<Categories xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="i1">
<EntityKey xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Data" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses" z:Id="i2">
<d3p1:EntityContainerName>eLearningDbEntities</d3p1:EntityContainerName>
<d3p1:EntityKeyValues>
<d3p1:EntityKeyMember>
<d3p1:Key>ID</d3p1:Key>
<d3p1:Value xmlns:d6p1="http://www.w3.org/2001/XMLSchema" i:type="d6p1:int">1</d3p1:Value>
</d3p1:EntityKeyMember>
</d3p1:EntityKeyValues>
<d3p1:EntitySetName>Categories</d3p1:EntitySetName>
</EntityKey>
<ID>1</ID>
<Name>e-Business</Name>
</Categories>
<Categories xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="i3">
<EntityKey xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Data" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses" z:Id="i4">
<d3p1:EntityContainerName>eLearningDbEntities</d3p1:EntityContainerName>
<d3p1:EntityKeyValues>
<d3p1:EntityKeyMember>
<d3p1:Key>ID</d3p1:Key>
<d3p1:Value xmlns:d6p1="http://www.w3.org/2001/XMLSchema" i:type="d6p1:int">2</d3p1:Value>
</d3p1:EntityKeyMember>
</d3p1:EntityKeyValues>
<d3p1:EntitySetName>Categories</d3p1:EntitySetName>
</EntityKey>
<ID>2</ID>
<Name>SADE</Name>
</Categories>
</ArrayOfCategories>

谢谢!

4

1 回答 1

0

您不应该直接传回您的数据库实体,而是创建一个可以传回的视图模型,将消息隔离到您关心在客户端接收的字段。例如

// Create a View Model to hold appropriate properties
public class MyViewModel
{
   public string PropertyA {get; set;}
   public string PropertyB {get; set;}
}

...

// Map your entity to the View Model and return it.
var viewModel = context.Categories.Select(
      e=>new MyViewModel(){ 
      PropertyA = e.SomeProperty,
      PropertyB = e.AnotherProperty          
   });
return viewModel;
于 2013-04-29T16:56:40.770 回答