Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping value-type collection in Entity Framework

Similar question: Mapping collection of strings with Entity Framework or Linq to SQL

I have a role class:

public class Role
{
    public int RoleID { get; set; }
    public virtual IList<string> Actions { get; set; }
}

I have a mapping table in the db, "RoleActionMapping" with the columns, "RoleID" and "Action". "RoleID" is a foreign key point to the Role table, and "Action" is a varchar. I cannot seem to setup my EF mapping to populate the Role class with the RoleActions.

Any ideas on how to achieve this? Thanks!

like image 313
reustmd Avatar asked Mar 03 '11 01:03

reustmd


1 Answers

EF doesn't offer such mapping.

If you want to map it you must use:

public class Role
{
  public int RoleID { get; set;}
  public virtual IList<RoleAction> Actions { get; set; } // you should initialize collection
}

public class RoleAction
{
  public int ActionId { get; set; } // PK must be defined or entity is readonly
  public string Action { get; set; }
  public virtual Role { get; set; }
}

You can further extend Role class to provied not mapped property returning IEnumerable<string> which will internally select data from Actions property.

But once you follow this approach you should consider model it as M:N relation between Role and Action entity.

like image 151
Ladislav Mrnka Avatar answered Oct 19 '22 10:10

Ladislav Mrnka