2017-12-04 6 views
0

quora 또는 stackoverflow와 같은 질의 응답 웹 사이트를 만들려고합니다. tagName이 이미 존재하는지 검색하기 위해 사용자 정의 메소드를 넣을 수 있습니다. 따라서 duplicate를 작성하기보다는 tagName을 선택할 수 있습니다. 나는 이미 이런 식으로 뭔가 보일 것입니다 아이디어가 :중복 된 변수를 방지하기 위해 SQL 데이터베이스를 검색하는 방법

var objectExists = _context.Tag.Find(a => a.Name == tag); 
if (objectExists == null) 
{ 
    _context.QuestionTag.Add(new QuestionTag(){Tag = new Tag(){ Name = tag }); 
} 

을하지만 난 parseTag 방법

public async Task BuildQuestion(string title, string body, string tags, ApplicationUser user) 
      { 
       var question = new Question 
       { 
        Title = title, 
        Body = body, 
        QuestionTags = ParseTags(tags), 
        User = user 
       }; 
       _context.Add(question); 
       await _context.SaveChangesAsync(); 
      } 

    public List<QuestionTag> ParseTags(string tags) 
    { 
     var tagList = tags.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList(); 
     var questionTags = new List<QuestionTag>(); 

     foreach(var tag in tagList) 
     { 
      questionTags.Add(new QuestionTag() 
      { 
       Tag = new Tag(){Name = tag}} 
      ); 
     } 
     return questionTags; 
    } 
+2

동일한 텍스트가있는 레코드가 있는지 확인하기 위해 먼저 SELECT 쿼리를 작성하면됩니다. 그리고/또는 필드에 고유 한 제약 조건을 넣어 중복 생성을 막습니다. – ADyson

+0

@ADyson (방금 제약 조건에 대해 말했을 때 미리 주석 처리) 아마도 SaveChangesAsync가 롤백을 수행하여 질문을 저장할 수 없기 때문일 것입니다. 나는 제약 조건을 반드시 가져야한다는 것에 강력히 동의합니다. 제약 조건을 준수했다면 업스트림 오류를 나타냅니다. –

+0

@ADyson 코딩 예제를 제공해 주시겠습니까? Pleeaasee ... 나는 밤새이 물건과 싸우고 있었고 오류가 계속 발생했습니다. – AllocSystems

답변

1

에 그 논리를 incoporate 수없는 것 어떻게 단지에 존재하지 않는 태그를 추가하는 방법에 대한 데이터베이스가 ParseTags()에 있습니까?

public List<QuestionTag> ParseTags(string tags) 
{ 
    var tagList = tags.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList(); 
    var questionTags = new List<QuestionTag>(); 
    var anyNewTags = false; //to see if we have to SaveChanges() 

    foreach(var tag in tagList) 
    { 
     //You should do the check and add your tags here 
     var objectExists = _context.Tag.Find(a => a.Name == tag); 
     if (objectExists == null) 
     { 
      //tag doesn't exist 
      //create a new tag, add it to db 
      //also add it to the tag list 

      var newTag = new QuestionTag() { Tag = new Tag() { Name = tag } }; 
      _context.QuestionTag.Add(newTag); 
      questionTags.Add(newTag); 

      //there is a new tag, we have to call SaveChanges() 
      anyNewTags = true; 
     } 
     else 
     { 
      //tag exists, just grab it, no need to add anything. 
      questionTags.Add(objectExists); 
     } 
    } 

    //do we have new tags, do we need to call SaveChanges()? 
    if (anyNewTags) _context.SaveChanges(); 

    return questionTags; 
} 
+0

을 참조하십시오. 고마워요! – AllocSystems

+0

안녕하세요, questionTags.Add (objecExists)에서 오류가 발생했습니다. Linq.IQuerable을 변환하는 것에 관한 것 – AllocSystems

+1

더 많은 정보를 게시하면 도움을 줄 수 있습니다. 예외는 무엇을 말합니까? – Mithgroth