我在ASP.Net WebApi项目中有以下控制器。 该模型使用Entity Framework生成。
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;
}
}
当从浏览器调用控制器时,我得到以下结果,但我想只得到Model的属性,而不是所有的上下文属性。有什么想法是错的吗?
<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>
谢谢!
答案 0 :(得分:0)
您不应该直接传回数据库实体,而是创建一个可以传回的视图模型,将消息隔离到您关心在客户端接收的字段。 e.g。
// 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;