0

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;
        }
    }

ブラウザーからコントローラーを呼び出すと、次の結果が得られますが、すべてのコンテキスト プロパティではなく、モデルのプロパティのみを取得したいと考えています。何が間違っているのですか?

<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 に答える