NPOCO:DELETE ()呼び出しがNullReferenceExceptionを投げるのはなぜですか?
質問
データベースから行を削除するには、npocoのdelete()メソッドを使用しようとしています。しかし、それはNullReferenceExceptionをスローするだけです。
私は回避策を見つけました、しかし、誰かがIDによって削除された組み込みの削除関数が私のために機能していない理由を誰かが知っているかどうか疑問に思います。これは複数のテーブルで起こります。すべてのテーブルには、[PrimaryKey("ID")]
デコレータを使用してモデル内にフラグが立てられたIDという標準の整数主キーがあります。
オブジェクト参照オブジェクトのインスタンスに設定されていません。
Delete<PurchaseItem>(id); // throws null reference exception.
Delete<PurchaseItem>("where id = @0", id); // works.
.
渡されているIDは有効ですアイテムがデータベースにあります。コードはSQLを実行する限り取得されません。
スタックトレース:
[NullReferenceException: Object reference not set to an instance of an object.]
NPoco.PocoDataFactory.ForObject(Object o, String primaryKeyName) in d:\Adam\projects\NPoco\src\NPoco\PocoDataFactory.cs:41
NPoco.Database.Delete(String tableName, String primaryKeyName, Object poco, Object primaryKeyValue) in d:\Adam\projects\NPoco\src\NPoco\Database.cs:1587
NPoco.Database.Delete(Object pocoOrPrimaryKey) in d:\Adam\projects\NPoco\src\NPoco\Database.cs:1598
Harmsworth.DAL.HarmsworthDB.DeletePurchaseItemFromBasketByID(Int32 id) in c:\inetpub\wwwroot\harmsworth\Website\classes\HarmsworthDAL.cs:224
Harmsworth.ViewBasketPage.RemoveItem(Int32 id) in c:\inetpub\wwwroot\harmsworth\Website\view-basket.aspx.cs:187
Harmsworth.ViewBasketPage.PurchaseItemsRepeater_ItemCommand(Object sender, RepeaterCommandEventArgs e) in c:\inetpub\wwwroot\harmsworth\Website\view-basket.aspx.cs:75
System.Web.UI.WebControls.Repeater.OnItemCommand(RepeaterCommandEventArgs e) +111
[more redundant trace info]
. 解決
どのタイプのid
が何であるかを指定していませんが、それがintであり、次のコードを持っていると仮定するつもりです:
var id = 12345;
Delete<PurchaseItem>(id);
.
どの呼び出しを呼び出します Delete<T>(object pocoOrPrimaryKey)
、コード:
public int Delete<T>(object pocoOrPrimaryKey)
{
if (pocoOrPrimaryKey.GetType() == typeof(T))
return Delete(pocoOrPrimaryKey);
var pd = PocoDataFactory.ForType(typeof(T));
return Delete(pd.TableInfo.TableName, pd.TableInfo.PrimaryKey, null, pocoOrPrimaryKey); // This is the method your code calls
}
.
どの順番にNPOCOを呼び出します。 Delete(string tableName, string primaryKeyName, object poco, object primaryKeyValue)
、コードは次のとおりです。
public virtual int Delete(string tableName, string primaryKeyName, object poco, object primaryKeyValue)
{
if (!OnDeleting(new DeleteContext(poco, tableName, primaryKeyName, primaryKeyValue))) return 0;
var pd = PocoDataFactory.ForObject(poco, primaryKeyName);
...
}
.
スタックトレースに従って例外をスローするPocoDataFactory.ForObject
メソッドとして、最初の2行だけを含めました。 ForObject(object o, string primaryKeyName)
.
public PocoData ForObject(object o, string primaryKeyName)
{
var t = o.GetType(); // This is where the exception comes from
...
}
これは何が起こっているのか(IDが12345であると仮定すると、テーブルはPURRIPEITEMとしてマッピングされ、主キーはIDとしてマッピングされています):
Delete<PurchaseItem>(pocoOrPrimaryKey : 12345);
Delete(tableName: "PurchaseItem", primaryKeyName: "Id", poco: null, primaryKeyValue: 12345);
PocoDataFactory.ForObject(o: null, primaryKeyName: Id);
.