在EF中插入/更新实体?

时间:2013-10-24 03:53:49

标签: c# entity-framework

我正在编写一个应该访问网站的抓取工具,从那里提取一些数据,然后将其存储到数据库中,问题是抓取工具还应该更新先前运行中已经找到的数据。

ParseDataPage返回EF POCO中从站点解析的信息,其中一个属性是唯一标识符(也是db表中的主键),如何告诉EF插入/添加对象?

class Program
{
    static void Main()
    {

        var context = (adCreatorEntities) DbContextFactory.GetInstance().GetDbContext<adCreatorEntities>();
        var crawler = new DataCrawler();            
        crawler.Login();
        var propertyIds = crawler.GetPropertyIds();

        foreach (var id in propertyIds)
        {
            var poco = crawler.ParseDataPage(id);
            context.Properties.Add(poco); //<-- How can I tell EF to update if the record exists or to insert it otherwise??
            context.SaveChanges();
        }

        context.SaveChanges();

        if (crawler.LoggedIn)
            crawler.Logout();
    }
}

2 个答案:

答案 0 :(得分:4)

您可以将实体状态设置为Modified,或者根据密钥的值将实体添加到DbSet

if(entity.propertyId <= 0)
{
    context.Properties.Add(poco); 
}
else
{
      context.Entry(poco).State = EntityState.Modified;
}

这是EF5的代码,EF4与设置对象状态略有不同

context.ObjectStateManager.ChangeObjectState(poco, EntityState.Modified);

答案 1 :(得分:1)

您可以使用以下代码检查记录是否存在,

 var entity= dataContext.Properties.Find(b => b.UniqueId == poco.UniqueId);
                    if (entity== null)
                    {
                        dataContext.Properties.Add(poco);
                    }
                    else
                    {
                       dataContext.Entry(entity).State = EntityState.Modified;
                    }
                   dataContext.SaveChanges();