2016-08-26 3 views
-1

私は、指定された列の更新を実装するためにefとreflectionを使用しています。 文字列が正確にexexuteすることができます。数字の列は1回更新すると変更され、2回目は0になりました。EF:データベースを更新するのがなぜ数値型列が0になるのですか?

public void UpdateSpecified(T entity) 
    { 
     var props = entity.GetType().GetProperties(); 
     foreach (var prop in props) 
     { 
      if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string)) 
      { 
       string propValue = prop.GetValue(entity, null) != null ? prop.GetValue(entity, null).ToString() : string.Empty; 
       if (!string.IsNullOrEmpty(propValue)) 
       { 
        DataContext.Entry<T>(entity).Property(prop.Name).IsModified = true; 
       } 
       else 
       { 
        DataContext.Entry<T>(entity).Property(prop.Name).IsModified = false; 
       } 
      } 
     } 

    } 

サービス層コード:

g.Id = good.Id; 
    g.GoodsQuantity = good.GoodsQuantity - 1; 
    goodsRepo.Attach(g); 
    goodsRepo.UpdateSpecified(g); 
    _repositoryFactory.Commit(); 
+0

2回目の更新前にdbからフェッチしていますか? – Oluwafemi

+0

こんにちは、私はそれを解決しました、私の答えを参照してください – MapleStory

答えて

-1

私はそれを解決しました。 まずあなたがのNullableタイプ

public float? GoodPrice { get; set; } 

    public float? GoodScore { get; set; } 

    public int? GoodsQuantity { get; set; } 

第二にあなたの番号タイプのモデルを定義する必要があります:あなたはこのようなあなたのEFマッピングクラスを変更する必要があります。

this.Property(x => x.GoodsQuantity).IsRequired(); 
    this.Property(x => x.GoodPrice).IsRequired(); 
    this.Property(x => x.GoodScore).IsRequired(); 

第三:あなたはこのようにコードを変更する必要があります:それは変更することができ

最後に
public void UpdateSpecified(T entity) 
    { 
     var props = entity.GetType().GetProperties(); 
     foreach (var prop in props) 
     { 
      if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string) 
       ||(prop.PropertyType.IsGenericType&& prop.PropertyType.GetGenericTypeDefinition()==typeof(Nullable<>))) 
      { 
       string propValue = prop.GetValue(entity, null) != null ? prop.GetValue(entity, null).ToString() : string.Empty; 
       if (!string.IsNullOrEmpty(propValue)) 
       { 
        DataContext.Entry<T>(entity).Property(prop.Name).IsModified = true; 
       } 
       else 
       { 
        DataContext.Entry<T>(entity).Property(prop.Name).IsModified = false; 
       } 
      } 
     } 

    } 

、それは

をcorrectly.xd
+0

それが必要な場合、なぜnullable型を指定しましたか? – Oluwafemi

関連する問題