2013-03-14 4 views
1

나는 때때로 디버깅을 수행 할 때 null null을 허용하지만 설정에 의해 게시물 갤러리를 제거 할 때 문제가 발생하지만 중단 점, 그것은 null 값이 아닙니다. 어떻게이 문제를 해결할 수 있습니까? 에스테 codigo : 여기엔티티 프레임 워크 4.3.1 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(); 

내가 갤러리

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

이것은 매우 분명하지 않습니다. "때로는 null을 허용하지만", "중단 지점 일 때 퇴각" 문제가 정확히 무엇입니까? –

+0

문제는 외래 키가 null 값을 허용하지 않는다는 것입니다. –

+0

확실하지 않지만 최선의 방법은 외래 키 null 값을받는 방법입니다. do {editPost.Galeria = null; } while (editPost.Galeria! = null);' –

답변

3
문제는 여기에 사실과 관련이있다

에 null을 넣어 어디 그 EF 것이다 기본적으로 게으른로드 탐색 속성,하지 않는 한 명시 적 열망로드 그들은 .Include()을 사용합니다.

느린 로딩을 사용하면 네비게이션 속성이 처음으로 액세스 할 때까지 null이됩니다. 처음 액세스하는 동안 EF는 데이터를 탐색 속성에로드하기 위해 db를 누 릅니다.

당신의 코드는 그렇게하지 않습니다. 속성이 지연로드되기 전에 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); 
관련 문제