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 回答