当我尝试使用Mvc的实体框架时。我想在创建数据库时插入一些数据,但是Fword类具有树属性。当我尝试将其添加到List或List时,在Seed方法中得到了 NullPointerException 。谁能告诉我我哪里出问题了?
这是DataAccess类
public class MyContext : DbContext
{
public MyContext () : base("MyContext")
{
Database.SetInitializer(new VeritabaniOlusturucu());
}
public DbSet<FWord> words { get; set; }
public DbSet<WordType> WT { get; set; }
public DbSet<WordFrequency> WF { get; set; }
}
在下面的类种子方法中,我得到了错误。
public class VeritabaniOlusturucu : CreateDatabaseIfNotExists<EWLContext>
{
protected override void Seed(MyContext context)
{
WType wt = new WType();
wt.Type = "determiner";
FWord fw = new FWord();
fw.Word = "try";
fw.WT.Add(wt);//I got here error
fw.WF.Add(new WordFrequency { Frequency = "B1" });//and here
fw.WF.Add(new WordFrequency { Frequency = "B2" });//and here
context.FWords.Add(fw);
context.SaveChanges();
}
}
这是实体类
[Serializable]
public class FWord
{
public FWord()
{
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public String Word { get; set; }
public List<WordType> WT { get; set; }
public List<WordFrequency> WF { get; set; }
}
[Serializable]
public class WordType
{
public WordType()
{
}
[Key]
public int Id { get; set; }
public String Type { get; set; }
public virtual FWord Freq { get; set; }
}
[Serializable]
public class WordFrequency
{
public WordFrequency()
{
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public String Frequency { get; set; }
public virtual FWord Freq { get; set; }
}
谢谢。
答案 0 :(得分:0)
您的列表为空。您必须实例化它,然后才能向其中添加项目。
protected override void Seed(MyContext context)
{
WType wt = new WType();
wt.Type = "determiner";
FWord fw = new FWord();
fw.Word = "try";
fw.WT = new List<WordType>();
fw.WT.Add(wt);
fw.WF.Add(new WordFrequency { Frequency = "B1" });//and here
fw.WF.Add(new WordFrequency { Frequency = "B2" });//and here
context.FWords.Add(fw);
context.SaveChanges();
}
答案 1 :(得分:0)
您的列表是未初始化的属性,除非您进行设置,否则它为null。如果即使未设置也要避免这种情况,请为其设置默认值:
public List<WordType> WT { get; set; } = new List<WordType>()
public List<WordFrequency> WF { get; set; } = new List<WordFrequency>();