猿问

实体框架-代码优先-无法存储List <String>

我写了这样的课:


class Test

{

    [Key]

    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

    public int Id { get; set; }

    [Required]

    public List<String> Strings { get; set; }


    public Test()

    {

        Strings = new List<string>

        {

            "test",

            "test2",

            "test3",

            "test4"

        };

    }

}


internal class DataContext : DbContext

{

    public DbSet<Test> Tests { get; set; }

}

运行后代码:


var db = new DataContext();

db.Tests.Add(new Test());

db.SaveChanges();

我的数据正在保存,但只是Id。我没有适用于“ 字符串”列表的任何表或关系。


我究竟做错了什么?我也尝试过制作Strings, virtual但是它什么都没有改变。


谢谢您的帮助。


慕妹3242003
浏览 689回答 3
3回答

MYYA

我知道这是一个古老的问题,Pawel提供了正确的答案,我只想显示一个代码示例,该示例演示如何进行一些字符串处理,并避免为原始类型的列表使用额外的类。public class Test{&nbsp; &nbsp; public Test()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _strings = new List<string>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "test",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "test2",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "test3",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "test4"&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }&nbsp; &nbsp; [Key]&nbsp; &nbsp; [DatabaseGenerated(DatabaseGeneratedOption.Identity)]&nbsp; &nbsp; public int Id { get; set; }&nbsp; &nbsp; private List<String> _strings { get; set; }&nbsp; &nbsp; public List<string> Strings&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get { return _strings; }&nbsp; &nbsp; &nbsp; &nbsp; set { _strings = value; }&nbsp; &nbsp; }&nbsp; &nbsp; [Required]&nbsp; &nbsp; public string StringsAsString&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get { return String.Join(',', _strings); }&nbsp; &nbsp; &nbsp; &nbsp; set { _strings = value.Split(',').ToList(); }&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答