1

投稿のギャラリーを設定で削除すると、デバッグ時にnull nullを受け入れることがあるのに困っているのですが、ブレークポイントでnull値でない場合は退却します。エステ・コディゴ:

 var postold = _postRepositorio.ObterPorId(postDto.Id);

        if (postold.ImagemCapa != postDto.ImagemCapa && !String.IsNullOrEmpty(postDto.ImagemCapa) && !String.IsNullOrEmpty(postold.ImagemCapa))
        {
            if (
                File.Exists(
                    System.Web.HttpContext.Current.Server.MapPath(
                        Path.Combine(ConfigurationManager.AppSettings["DiretorioImagem"], postDto.ImagemCapa))))
            {
                File.Delete(
                    System.Web.HttpContext.Current.Server.MapPath(
                        Path.Combine(ConfigurationManager.AppSettings["DiretorioImagem"], postold.ImagemCapa)));
            }
        }
        var editPost = AutoMapper.Mapper.Map(postDto, postold);
        editPost.CategoriaPost = _categoriaPostRepositorio.ObterPorId(postDto.CategoriaPost);

        editPost.Galeria = postDto.Galeria == 0 ? null : _galeriaRepositorio.ObterPorId(postold.Id);

        _postRepositorio.Editar(editPost);

        _contexto.SaveChanges();

ギャラリーにnullを入れる場所はここにあります

 editPost.Galeria = postDto.Galeria == 0? null: _galeriaRepositorio.ObterPorId (postold.Id);
4

1 に答える 1

3

ここでの問題は、 を使用して明示的に熱心にロードしない限り、EF が既定でナビゲーション プロパティを遅延ロードするという事実に関係しています.Include()

遅延読み込みでは、ナビゲーション プロパティはnull初めてアクセスしようとするまで続きます。その最初のアクセス中に、EF はデータベースにアクセスして、データをナビゲーション プロパティに読み込みます。

あなたのコードはそれをしていません。プロパティが遅延ロードされる前に null に設定しようとしています。代わりにこれを試すことができます:

var tenerGaleria = editPost.Galeria == null; // this will trigger the lazy load
if (postDto.Galeria == 0 && tenerGaleria)
    editPost.Galeria = null; // now setting it to null should work
else if (postDto.Galeria != 0)
  editPost.Galeria = _galeriaRepositorio.ObterPorId(postold.Id);

エンティティが外部キーも公開している場合は、ナビゲーション プロパティの遅延/積極的な読み込みを心配することなく、それを null に設定できます。

if (postDto.Galeria == 0)
    editPost.GaleriaId = null; // set the FK to null
else
    editPost = _galeriaRepositorio.ObterPorId(postold.Id);
于 2013-03-14T19:04:23.697 に答える