gpt4 book ai didi

c# - 如何在 MySql 数据库中存储 List

转载 作者:行者123 更新时间:2023-11-29 00:19:55 25 4
gpt4 key购买 nike

我在 Role Access Base Control 项目中工作,我需要在 Mysql 数据库中为每个角色存储一个列表。这是我的代码...

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>();
}
}

有我要存储的每个角色的权限列表 public virtual List<string> Permissions { get; set; }但是当我尝试在我的角色数据库中插入一些记录时,表中没有字符串列表的列 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

}

这是 MySql 数据库角色表在插入后显示的内容:

enter image description here

var l = new List<string>() { "Permission1", "Permission2", "Permission3" };我要插入的内容不在表中。

我正在使用 Entity Framework 5 + MySql db + C#

希望玩具达人能帮帮我!

最佳答案

您可以在私有(private)属性中将角色存储为单个逗号分隔的字符串:

并从 RolesInternal 中读取 Roles 属性:

    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); }
}

有关映射私有(private)属性的示例代码:

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

关于c# - 如何在 MySql 数据库中存储 List<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21421771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com