I am working on a project with ASP.Net MVC3 EF4.1 and relationships between tables through foreign keys. I am using the database first approach and have three tables: Calendar, Calendar Users and Users. The relationship is that a Calendar can have many users and users can have many calendars.
When someone is creating the calendar he/she is also supposed to select the number of users that will have access to the calendar. But now when I am about to save the changes to the database in the controller thats when I get confused. In the generated classes there are also virtual ICollections that I suppose represent the foreign keys somehow. But I can’t figure out how I am supposed to handle them? So how is it supposed to work? Should I be able to add the changes to the virtual ICollections and then just do db.SaveChanges() and it will work by itself or am I supposed too handle that manually?
If I am supposed to handle it manually should I then add the users, add the calendar and then add the keys in the CalendarUsers table to bind them together? I’ve seen some examples from code first where they have clarified the relationship by entering code in the OnModelCreating method but when using Database first it just contains: throw new UnintentionalCodeFirstException();? Hoping you perhaps can clarify it for me a bit.
Added the classes generated by the DBcontext Generator below:
public partial class Calendar
{
public Calendar()
{
this.CalendarUsers = new HashSet<CalendarUser>();
}
public int CalendarId { get; set; }
public string CalendarTitle { get; set; }
public string CalendarDescription { get; set; }
public long UserId { get; set; }
public virtual User User { get; set; }
public virtual ICollection<CalendarUser> CalendarUsers { get; set; }
}
public partial class CalendarUser
{
public int CalendarUserId { get; set; }
public int CalendarId { get; set; }
public long UserId { get; set; }
public Nullable<bool> IsAdmin { get; set; }
public virtual Calendar Calendar { get; set; }
public virtual User User { get; set; }
}
public partial class User
{
public User()
{
this.Calendars = new HashSet<Calendar>();
this.CalendarUsers = new HashSet<CalendarUser>();
}
public long UserId { get; set; }
public string Name { get; set; }
public virtual ICollection<Calendar> Calendars { get; set; }
public virtual ICollection<CalendarUser> CalendarUsers { get; set; }
}
You can just create a new relationship between existing
CalendarandUserby setting the foreign key properties in a new instance of theCalendarUser: