Rafael Reyes
Rafael Reyes

Reputation: 2655

How to store a List<string> in MySql db

I'm working in a Role Access Base Control project and I need to store a list in a Mysql db for every single role. Here is my code...

public class LoginModel
{
    [Key]
    public int lm_Id { get; set; }
    public string User { get; set; }
    public string Pass { get; set; }
    public virtual ICollection<Roles> roles { get; set; }

    public LoginModel()
    {
        roles = new HashSet<Roles>();
    }
}

public class Roles
{
    [Key]
    public int role_Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<LoginModel> Users { get; set; }
    public virtual List<string> Permissions { get; set; }

    public Roles(){
       Users = new List<LoginModel>();
    }
}

There is the list of permissions per Role I want to store public virtual List<string> Permissions { get; set; } but when I try to insert some records in my Role db Table doesn't have a column for the list of strings List<string> Permissions { get; set; }

using (var db = new MySqlContext())
{

    #region insert


    var l = new List<string>() { "Permission1", "Permission2", "Permission3" };
    db.LoginModel.Add(

        new LoginModel
        {
            User = "rafa",
            Pass = "123",
            roles =
            {
                new Roles {Name = "usuario", Permissions = l},
                new Roles {Name = "usuario2", Permissions = l}
            }

        }

    );

    db.LoginModel.Add(
        new LoginModel
        {
            User = "Ralph",
            Pass = "123",
            roles =
            {
                new Roles {Name = "Admin", Permissions = l},
                new Roles {Name = "Admin2", Permissions = l}
            }

        }

    );
    db.SaveChanges();

    #endregion

}

And here is what the MySql db Roles Table shows after insert:

enter image description here

The var l = new List<string>() { "Permission1", "Permission2", "Permission3" };that I'm inserting is not in the table.

I'm using Entity Framework 5 + MySql db + C#

Hope toy guys can help me!

Upvotes: 1

Views: 3728

Answers (1)

dksh
dksh

Reputation: 194

you can store roles in private property as single comma separated string:

and have Roles property read from RolesInternal:

    private string RolesInternal { get; set; }

    [NotMapped]
    public List<string> Roles
    {
        get { return RolesInternal.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(t => t).ToList(); }
        set { RolesInternal = string.Join(",", value); }
    }

For sample code on mapping private properties:

http://romiller.com/2012/10/01/mapping-to-private-properties-with-code-first/

Upvotes: 1

Related Questions