【发布时间】:2019-02-14 19:42:54
【问题描述】:
当我尝试使用 Mvc 使用实体框架时。我想在创建数据库时插入一些数据,但 Fword 类具有树属性。当我尝试添加到它的 List 或 List 时,我在 Seed 方法中得到 NullPointerException。谁能告诉我哪里出错了?
这里是数据访问类
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; }
}
谢谢。
【问题讨论】:
标签: c# entity-framework model-view-controller