4

Jsonリクエストのデータをシリアル化するために、必要なデータを単純な匿名型に選択しようとしています。

using (var dbContext = new DataContext())
{
    var vals = dbContext.Primaries.Select(p => new
    {
       Name = p.Name,
       Secondary = p.SecondaryId.HasValue ? new { Name = p.Secondary.Name } : null
    });
}

しかし、vals で列挙子を呼び出すと、次の例外が発生します

Unable to create a null constant value of type 'Anonymous type'. Only entity types, enumeration types or primitive types are supported in this context.

Secondary外部キーがnullの場合、実際にはnullである必要があります。select ステートメントから直接匿名を null にする方法を教えてください。

私のアイデアの解決策は、中間データセットを処理することなく、結果のデータを直接シリアル化できるようにすることです。

4

2 に答える 2

0

私はそれ自体に「解決策」を持っていません。この問題を回避するために、単純にセカンダリ エンティティ全体を投影しました。私はこの解決策に満足していません。

using (var dbContext = new DataContext())
{
    var vals = dbContext.Primaries.Select(p => new
    {
       Name = p.Name,
       Secondary = p.Secondary
    });
}

明らかに、エンティティ全体を射影することは「SELECT *」に似ています。これは悪い習慣です。また、実際のクエリによっては、うまくいかない場合があります。

于 2013-11-04T17:54:49.337 に答える
0

匿名オブジェクトが null プロパティを持つ可能性がある場合は、常に匿名を返すことで、これを回避できます。

using (var dbContext = new DataContext())
{
    var vals = dbContext.Primaries.Select(p => new
    {
       Name = p.Name,
       Secondary = new { Name = p.SecondaryId.HasValue ? p.Secondary.Name : null }
    });
}

本当に null にしたいSecondary場合p.SecondaryIdは、次のように追加できます。

//ToList allows you to work with LINQ to Objects rather than Linq to Entities.  
//However, you'll generally want to call ToList() last for performance reasons.
var valsCleaned = vals.ToList()
                      .Select(v => { 
                                       if(v.Secondary.Name == null)
                                       {
                                           v.Secondary == null;
                                       }
                                       return v;
                                   });
于 2013-07-23T03:48:09.840 に答える