1

I have two Model classes to be created using Entity Framework: Skill and Activity. The following are the definitions of each:

Skill.cs

public class Skill
{
    public int Id { get; set; }
    public String Name { get; set; }
}

Activity.cs

public class Activity
{
    public int Id { get; set; }
    public String Name { get; set; }
    public virtual List<Skill> RequiredSkills { get; set; }
}

Ideally, in the database, I'd want the Activity to be linked via foreign key to a association entity (e.g. SkillActivityAssoc) and the Skill not to have to do anything with it. I don't need to track which activities need a certain skill. I just need to track what skills are needed for each activity thus explaining why I don't have a List in the Skill class. I hope that made sense.

My question is: Is this the right way to go about doing this? When I update the RequiredSkills property of Activity via:

 activity.RequiredSkills = someInstanceOfRequiredSkillsList;
 dbcontext.Entry(activity).State = EntityState.modified;
 dbcontext.SaveChanges();

.., it doesn't work. I'm already speculating that it's because I'm not able to update the association entity. Moreover, my current implementation has a virtual List<Activity> property in the Skill class which I want to get rid of. How do I go about changing my model design and how do I update RequiredSkills accordingly?

Thank you in advance!

Vandenn
  • 119
  • 1
  • 5

1 Answers1

0

virtual is for lazy loading and track changes in EF. You can read more about it here: Understanding code first virtual properties. You should also read MSDN documentation about loading entities in EF: https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx

Since you want to have more than one Skills in each Activity and each Skills can be in more than one Activity as well, you have a many-to-many relantionship. Please read this example: How to create a many-to-many mapping in Entity Framework? and this http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

Ricardo Serra
  • 374
  • 2
  • 11
  • Thank you very much for the answer. However, is it possible to create this many-to-many relationship with Skill not having a reference to the Activities that use it? Meaning, can I have it such that Activity has a navigation property of Skills but Skills is not tracking its linked Activities? – Vandenn Mar 16 '17 at 09:48
  • Yes, you can have. Because collection properties in EF are navigation properties. Please read more about it here: https://stackoverflow.com/questions/16718699/map-many-to-many-relationship-without-navigation-property and MSDN documentation: https://msdn.microsoft.com/en-us/library/jj713564(v=vs.113).aspx – Ricardo Serra Mar 16 '17 at 10:17
  • Thank you very much for your answer again! :) – Vandenn Mar 17 '17 at 13:18