Entity Framework 5 on .NET 4.0 - DatabaseGenerated

2019-01-23 14:51发布

I need to use EF5 on .NET 4 and I've run into a reference issue when mapping my class with HasDatabaseGenerationOption.Identity which doesn't exist in the 4.0 version of the library.

The following is failing:

this.Property(t => t.DeploymentLogId)
              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Does anyone know of a work around?

5条回答
我命由我不由天
2楼-- · 2019-01-23 15:36

Using NuGet to add EntityFramework to a project that targets .NET 4.5, will add EntityFramework 5.0.

If you later change the project to target .NET 4.0, EntityFramework 5.0 is still referenced.

To fix it, use NuGet to uninstall EntityFramework and add it back, also in NuGet. This will add EntityFramework 4.4 which is the last supported version for .NET 4.0.

If it still does not work there may be some references to the specific EF version in App.config. These can be removed.

查看更多
干净又极端
3楼-- · 2019-01-23 15:37

We had that problem very recently on an old project, and what we did was just

  • delete the EntityFramework reference in the project
  • right click on the project, do a Manage NuGet packages, go to the Updates category, and click Update on the Entity Framework item that was there in the list to version 6
查看更多
Viruses.
4楼-- · 2019-01-23 15:40

The namespace changed in EF 5.0. Try adding this:

using System.ComponentModel.DataAnnotations.Schema;
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-23 15:41

System.ComponentModel.DataAnnotations.Schema has only been a part of the .NET Framework since 4.5

If you're using 4.0 then Entity Framework will provide it for you. If you look at the source code of DatabaseGeneratedOption and the other files, you'll see that their code is wrapped in a conditional

#if NET40
...
#endif
查看更多
男人必须洒脱
6楼-- · 2019-01-23 15:47

Have you tried using a data annotation?

public class DeploymentLog
{
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DeploymentLogId { get; set; }
查看更多
登录 后发表回答