实体框架未保存新项目

时间:2018-06-22 15:43:33

标签: c# entity-framework entity-framework-6

我有个奇怪的问题。下面的代码不会保存新的LookupGroup对象

LookupGroup lookup = null;

using (var db = new WaybackDbContext())
{
    lookup = db.LookupGroups.SingleOrDefault(x => x.Name.Equals(lookupName, StringComparison.InvariantCultureIgnoreCase));

    if (lookup == null)
    {
        lookup = new LookupGroup
        {
            Name = lookupName
        };
        db.SaveChanges();
    }

}

LookupGroup已启动,但未保存,其ID为0。

阻止它保存的原因是什么?

1 个答案:

答案 0 :(得分:5)

将其添加到上下文:

if (lookup == null)
{
    lookup = new LookupGroup
    {
        Name = lookupName
    };
    db.LookupGroups.Add(lookup);
    db.SaveChanges();
}