2012-07-25 6 views
10

다음 엔터티 프레임 워크 코드의 첫 번째 코드가 있습니다. 테이블이 작성되고 데이터가 삽입됩니다. 그러나 클럽 테이블에는 중복 기록이 있습니다.엔티티 프레임 워크 : 다 대다 관계의 중복 레코드

내 작업은 다음과 같습니다 -

  1. 클럽 작성 응용 프로그램 어떻게 중복 항목을 방지 할 수있는 사람이 응용 프로그램

를 사용

  • 만들기 사람을 사용하여 클럽을 만드시겠습니까?

    enter image description here

    static void Main(string[] args) 
        { 
         Database.SetInitializer<NerdDinners>(new MyInitializer()); 
    
         CreateClubs(); 
         InsertPersons(); 
    
        } 
    
        public static void CreateClubs() 
        { 
    
         string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30"; 
         using (var db = new NerdDinners(connectionstring)) 
         { 
    
          Club club1 = new Club(); 
          club1.ClubName = "club1"; 
    
          Club club2 = new Club(); 
          club2.ClubName = "club2"; 
    
          Club club3 = new Club(); 
          club3.ClubName = "club3"; 
    
          db.Clubs.Add(club1); 
          db.Clubs.Add(club2); 
          db.Clubs.Add(club3); 
    
          int recordsAffected = db.SaveChanges(); 
    
    
         } 
        } 
    
        public static Club GetClubs(string clubName) 
        { 
         string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30"; 
         using (var db = new NerdDinners(connectionstring)) 
         { 
    
          //var query = db.Clubs.Where(p => p.ClubName == clubName); 
          var query = db.Clubs.SingleOrDefault(p => p.ClubName == clubName); 
          return query; 
         } 
        } 
    
        public static void InsertPersons() 
        { 
         string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30"; 
         using (var db = new NerdDinners(connectionstring)) 
         { 
    
          Club club1 = GetClubs("club1"); 
          Club club2 = GetClubs("club2"); 
          Club club3 = GetClubs("club3"); 
    
          Person p1 = new Person(); 
          p1.PersonName = "Person1"; 
    
          Person p2 = new Person(); 
          p2.PersonName = "Person2"; 
    
          List<Club> clubsForPerson1 = new List<Club>(); 
          clubsForPerson1.Add(club1); 
          clubsForPerson1.Add(club3); 
    
          List<Club> clubsForPerson2 = new List<Club>(); 
          clubsForPerson2.Add(club2); 
          clubsForPerson2.Add(club3); 
    
          p1.Clubs = clubsForPerson1; 
          p2.Clubs = clubsForPerson2; 
    
          db.Persons.Add(p1); 
          db.Persons.Add(p2); 
    
          int recordsAffected = db.SaveChanges(); 
    
    
         } 
        } 
    

    도메인

    public class Person 
    { 
        public int PersonId { get; set; } 
        public string PersonName { get; set; } 
        public virtual ICollection<Club> Clubs { get; set; } 
    } 
    
    public class Club 
    { 
        public int ClubId { get; set; } 
        public string ClubName { get; set; } 
        public virtual ICollection<Person> Members { get; set; } 
    } 
    
    //System.Data.Entity.DbContext is from EntityFramework.dll 
    public class NerdDinners : System.Data.Entity.DbContext 
    { 
    
        public NerdDinners(string connString): base(connString) 
        { 
    
        } 
    
        protected override void OnModelCreating(DbModelBuilder modelbuilder) 
        { 
         //Fluent API - Plural Removal 
         modelbuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
        } 
    
        public DbSet<Person> Persons { get; set; } 
        public DbSet<Club> Clubs { get; set; } 
    
    } 
    
  • +1

    두 번 실행 했 다음을 참조하십시오? – podiluska

    +0

    @podiluska. 아니, 한번만 쳤어. – Lijo

    답변

    18

    문제 더 많은 컨텍스트를 만드는 것입니다.

    먼저 클럽을 만드십시오. 괜찮아. 그러나 사람을 만들면 GetClubs을 통해 클럽을 가져 오지만 각 클럽마다 실제 엔티티 프레임 워크 컨텍스트를 처분하므로 분리 된 엔티티로 끝납니다. InsertPersons에 새로운 사람에게 분리 된 클럽 엔티티를 추가하면 실제 상황에서 클럽이 신생 클럽이라고 생각할 것입니다.

    그래서 사람을 클럽에 추가 할 때 실제로 새로운 클럽을 만듭니다.

    이것은 엔티티 프레임 워크가 변경 사항을 추적하고 컨텍스트 당 엔티티를 관리하기 때문입니다. 엔티티를 포함하지 않은 컨텍스트에 엔티티를 추가하면 엔티티가 새 엔티티처럼 취급됩니다. 물론

    static void Main(string[] args) 
    { 
        Database.SetInitializer<NerdDinners>(new MyInitializer()); 
    
        string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30"; 
        using (var db = new NerdDinners(connectionstring)) 
        { 
         CreateClubs(db); 
         InsertPersons(db); 
        } 
    
    } 
    
    public static void CreateClubs(NerdDinners db) 
    { 
        Club club1 = new Club(); 
        club1.ClubName = "club1"; 
    
        Club club2 = new Club(); 
        club2.ClubName = "club2"; 
    
        Club club3 = new Club(); 
        club3.ClubName = "club3"; 
    
        db.Clubs.Add(club1); 
        db.Clubs.Add(club2); 
        db.Clubs.Add(club3); 
    
        int recordsAffected = db.SaveChanges(); 
    } 
    
    public static Club GetClubs(string clubName, NerdDinners db) 
    { 
        //var query = db.Clubs.Where(p => p.ClubName == clubName); 
        var query = db.Clubs.SingleOrDefault(p => p.ClubName == clubName); 
        return query; 
    } 
    
    public static void InsertPersons(NerdDinners db) 
    { 
        Club club1 = GetClubs("club1", db); 
        Club club2 = GetClubs("club2", db); 
        Club club3 = GetClubs("club3", db); 
    
        Person p1 = new Person(); 
        p1.PersonName = "Person1"; 
    
        Person p2 = new Person(); 
        p2.PersonName = "Person2"; 
    
        List<Club> clubsForPerson1 = new List<Club>(); 
        clubsForPerson1.Add(club1); 
        clubsForPerson1.Add(club3); 
    
        List<Club> clubsForPerson2 = new List<Club>(); 
        clubsForPerson2.Add(club2); 
        clubsForPerson2.Add(club3); 
    
        p1.Clubs = clubsForPerson1; 
        p2.Clubs = clubsForPerson2; 
    
        db.Persons.Add(p1); 
        db.Persons.Add(p2); 
    
        int recordsAffected = db.SaveChanges(); 
    } 
    

    는이 코드의 구조를 리팩토링,하지만 난 내 작업에 대해 하나의 EF 컨텍스트를 사용하는 것이주의하시기 바랍니다해야합니다

    사실,이 같은 (안 테스트)를 수행해야합니다. @PeterPorfy

    +0

    내 편집 및 코드 샘플보기 –

    +0

    해당 코드 샘플에는 EF 컨텍스트가 하나만 있습니다. 별도의 EF 컨텍스트가 필요합니다. 이견있는 사람? – Lijo

    +1

    실제 컨텍스트가 아닌 다른 소스의 엔티티를 사용하려면 엔티티를 연결해야합니다. http://msdn.microsoft.com/en-us/library/bb896271.aspx –

    0

    덕분에 또한

    Exception of type 'System.ObjectDisposedException' 내가 이전 컨텍스트에서 개체를 부착

    ((IObjectContextAdapter)db).ObjectContext.Attach((IEntityWithKey)entity); 
    

    을 사용 읽어 보시기 바랍니다.

    내가 사용한 IEntityWithKey의 한 예는 다음과 같습니다. 이 방법에 문제가 있으면 의견을 말하십시오.

    public class Person : IEntityWithKey 
    { 
        public int PersonId { get; set; } 
        public string PersonName { get; set; } 
    
        public EntityKey EntityKey { get; set; } 
    } 
    

    또한

    1. Problem with SaveChanges() Entity Framework 4.1
    2. Entity Framework Updating Many-To-Many Relationships - POCO

    +0

    downvote 사용자 - 관심이 있습니다. 왜 downvote가 있는지보십시오. 이 대답에 문제가 있습니까? – Lijo

    +0

    나는 올바른 것으로 표시된 피터의 대답을 선호한다고 생각합니다. 그냥 말해. – Miro

    +0

    나는 downvoted하지 않았습니다. – Miro

    관련 문제