none
EF4.3.1: how to set up many-to-many relationship between existing entities? RRS feed

  • Question


  • I got trouble when i want to  set up relationship between some existing entities and another one.

    Here is these two entity classes of mine

    public class Task : Entity
    {      
            //....
    
            public virtual ICollection<Person> Assignees { get; set; }
           
    }
        public class Person : Entity
        {
            //....
          
            public virtual ICollection<Task> AcceptedTasks { get; set; }
    
        }

    And this is my mapping configuration:

     HasMany(t => t.Assignees)
    .WithMany(p => p.AcceptedTasks)
    .Map(m =>{
                    m.MapLeftKey("TaskId").MapRightKey("PersonId").ToTable("Person_AcceptedTask");
    });
     

    the problem goes here:

    public void DesignateTask(Domain.Model.Task task, IEnumerable<Domain.Model.Person> persons, Domain.Model.Person charge = null)
            {
                try
                {
                    if (charge == null || charge.IsTransient())
                    {
                        charge = persons.FirstOrDefault();
                    }
    
                    if (!charge.IsTransient())
                    {
                        if (task.Assignees == null)
                            task = TaskRepository.GetTaskWithAssignees(task.Id);
    
                        
                        task.InChargeId = charge.Id;
                        foreach (var p in persons)
                        {
                            if (p != null)
                                task.Assignees.Add(p);
                        }
    
                        TaskRepository.UnitOfWork.Commit();//call:SaveChanges();
                    }
    
                }
                catch (Exception)
                {
                    
                    throw;
                }
            }

    The parameters of the incoming task and persons are existing entities in the database. I just want to build relationships between these entities (originally no relation).

    But the code  above will  insert  a group of persons into the database  , and the ralationship will established between the old "task" and the new added "persons"....

    what should I do to make this code work as I wished?

    Thursday, May 31, 2012 11:47 AM

Answers

  • Hi Fiis,

    Welcome to MSDN Forum.

    I'm not clear about the 'DesignateTask' method. Creating relationship between two entities in the database, in the common way, we often query out the two entities and assign one to the other entity's navigation property, based on this case, add one into the others' navigation property collection, then, call SaveChanges to persist.

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Sunday, June 3, 2012 2:37 PM
    Moderator