Save a relation with between two entities an N-N association

后端 未结 2 1031
青春惊慌失措
青春惊慌失措 2021-01-03 03:01

I\'ve a Entity Framework 4.0, with poco object. the edmx model file is generated from the database.

This datacontext is accessed through WCF service, it\'s only mean

相关标签:
2条回答
  • 2021-01-03 03:21

    If you want to avoid loading the objects from the database first you can do it like this(Code taken from one of my aplications so you will have to adapt it):

        public void AddAndRemovePersons(int id, int[] toAdd, int[] toDelete)
        {
            var mailList = new MailList { ID = id, ContactInformations = new List<ContactInformation>() };        
            this.db.MailLists.Attach(mailList);
    
            foreach (var item in toAdd)
            {
                var ci = new ContactInformation { ID = item };
                this.db.ContactInformations.Attach(ci);
                this.db.ObjectStateManager.ChangeRelationshipState(mailList, ci, ml => ml.ContactInformations, System.Data.EntityState.Added);
            }
    
            foreach (var item in toDelete)
            {
    
                var ci = new ContactInformation { ID = item };
                this.db.ContactInformations.Attach(ci);
                this.db.ObjectStateManager.ChangeRelationshipState(mailList, ci, ml => ml.ContactInformations, System.Data.EntityState.Deleted);
            }
        }
    

    I found deleting the relationship as hard as creating it so I left that code in there. One thing about this solution is that both the maillist and the contacts exist prior to this function being run. I attach them to make the state manager track them.

    If you are adding new objects that you also want to save you would use the

    this.db.MailLists.AddObject(you new item here)

    I hope that helps!

    0 讨论(0)
  • 2021-01-03 03:28

    Just a thought... how are the keys setup in the Right_Group table? If you use both IDRight and IDGroup together as primary key - this problem might occur. One suggetion is to add a new column (ID) into the Right_Group table, and having this ID as the primary key. Then use foreign keys on the other columns (IDRight, IDGroup) respectivly.

    0 讨论(0)
提交回复
热议问题