0

I'm having problems submitting data on the 3nd navigational property of an entity framework code first app.

My model is like this: (assume there is a model called User and Company)

public enum UserCompanyRoleType
{
    Administrator,
    Creator,
    Follower
}
/// <summary>
/// User that belongs to a company
/// </summary>
public class UserCompany
{

    public int UserCompanyId { get; set; }

    public virtual User User { get; set; }
    public virtual int UserId { get; set; }

    public virtual Company Company { get; set; }
    public virtual int CompanyId { get; set; }

    public virtual IEnumerable<UserCompanyRole> Roles { get; set; }
}

public class UserCompanyRole
{

    public virtual int UserCompanyRoleId { get; set; }
    public UserCompanyRoleType RoleType { get; set; }

    public virtual UserCompany UserCompany { get; set; }
    public virtual int UserCompanyId { get; set; }

}

Here is the service code:

var creator = new UserCompany { UserId = userId };
//add the user as both creator and admin
creator.Roles = new List<UserCompanyRole> { new UserCompanyRole{RoleType = UserCompanyRoleType.Creator}}; //somehow this does not reach the database

company.Users = new List<UserCompany>();
company.Users.Add(creator);

db.Companies.Add(company);
db.SaveChanges();

This saves both the company and the related usercompany, but the 2 roles are not saved. How do I save the 2 roles at the line i commented?

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

1 Answers1

1

You need to set Roles property to be of ICollection<UserCompany> type.

public class UserCompany
{

    public int UserCompanyId { get; set; }

    public virtual User User { get; set; }
    public virtual int UserId { get; set; }

    public virtual Company Company { get; set; }
    public virtual int CompanyId { get; set; }

    public virtual ICollection<UserCompanyRole> Roles { get; set; }
}

Enums are not supported in EF 4.1 so you will have use an int field to map that property.

Eranga
  • 32,181
  • 5
  • 97
  • 96
  • Why does ICollection work over IEnumerable? Should I change all my code to that? – Shawn Mclean Sep 17 '11 at 02:08
  • @Lol Check [Why does the entity framework need an ICollection for lazy loading](http://stackoverflow.com/questions/2866881/why-does-the-entity-framework-need-an-icollection-for-lazy-loading) – Eranga Sep 17 '11 at 02:12