如何在Entity Framework 4.4中实现DBSet.AddOrUpdate?

时间:2013-08-01 10:41:11

标签: entity-framework code-first

回应Slauma对我的问题about running applications that use EF on Windows XP 的回答我将我的应用程序从Entity Framework 5.0转换回使用Entity Framework 5.0和目标框架.NET 4.0(也称为Entity Framework 4.4)

但是我遇到以下错误;

System.Data.Entity.DbSet<MyEntity> does not contain a definition for AddOrUpdate 
and no extension method of a type System.Data.Entity.DbSet<MyEntity> accepting a 
first argument of type System.Data.Entity.DbSet<MyEntity> could be found.
(Are you missing a using directive or assembly reference )

我已尝试搜索此错误消息的片段,但没有取得多大成功。 奇怪的是4.4甚至没有提到in this Microsoft link EF4.4甚至没有SO标签

2 个答案:

答案 0 :(得分:31)

您必须添加...

using System.Data.Entity.Migrations;

...到您的代码文件中AddOrUpdate可用。它是extension method of IDbSet<T>,在IDbSetExtensions命名空间的System.Data.Entity.Migrations类中实现。

答案 1 :(得分:4)

当您enable migrations获得MVC5 Web应用程序时,您会在配置的种子方法中获得以下注释:

//  You can use the DbSet<T>.AddOrUpdate() helper extension method 

我最初对此用户是DbSet<MyEntity>.AddOrUpdate()。这将导致与此问题中提出的错误消息(并且正确地)相同的错误消息。 修复是读取注释的其余部分并使用传递给种子函数的上下文参数:

    context.MyEntity.AddOrUpdate();