2017-02-04 3 views
0

Guid IDを持つクラスがあります。Entity Framework Web ApiおよびDbContextでGUID IDを使用しています。動作しません。

public class Product { 
    public Guid Id {get;set;} 
} 

私はこのコンテキストをWebアプリケーションで使用しています。

public class ProductController : ApiController 
{ 
     readonly ProductContext database = new ProductContext(); 

     public IHttpActionResult Get(string id){ 
       database.find(id); // does not find. 
     } 
} 

アクションパラメータをguidとして変更すると、それが検出されます。

 public IHttpActionResult Get(Guid id){ 
       database.find(id); // finds. 
     } 

ユーザが無効なidパラメータを送信した場合、アプリケーションは例外をスローします。

パラメータ辞書は 非NULL可能タイプのパラメータ 'ID' のヌルエントリを含む '可能System.Guid' メソッド ため「(可能System.Guid)を取得System.Web.Http.IHttpActionResult

文字列としてidのプロパティをすべて作成する必要がありますか?どの方法が最善ですか?

答えて

2

あなたはGUIDにGuid?

public IHttpActionResult Get(Guid? id) 
{ 
    if (id.HasValue) 
    { 
     database.find(id.Value); // finds. 
    } 
    else 
    { 
     // invalid ID 
    } 
} 
+0

これは良い答えです。 –

+0

nullalable Guidインスタンスはdefalutモデルバインダーによってバインドされますか? – barteloma

+0

Nullable型は正しく処理する必要があります。問題がある場合は、ルーティングがどのように設定されているかを確認することができます。 – dana

0

キャスト文字列を使用することを試みることができます。

public class ProductController : ApiController 
    { 
      readonly ProductContext database = new ProductContext(); 

      public IHttpActionResult Get(string id){ 

        database.find(new Guid(id)); 
      } 
    } 
関連する問題