C# 为什么`DatabaseGenerated(DatabaseGeneratedOption.Identity)` 在MVC 4 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11300883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:18:45  来源:igfitidea点击:

Why `DatabaseGenerated(DatabaseGeneratedOption.Identity)` doesn't work in MVC 4

c#entity-frameworkef-code-firstasp.net-mvc-migration

提问by ahmadali shafiee

I was trying to move my MVC 3 project to MVC 4 but when I wanted to move this model:

我试图将我的 MVC 3 项目移动到 MVC 4 但是当我想移动这个模型时:

public class Link
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid ID { get; set; }

    [DisplayName("Shorted URL")]
    public string SURL { get; set; }

    [DisplayName("General Link")]
    public string OriginalURL { get; set; }

    [DisplayName("Click Count")]
    public int ClickCount { get; set; }
}

public class LinkDBContext : DbContext
{
    public DbSet<Link> Links { get; set; }
}

I got error with [System.ComponentModel.DataAnnotations.(DatabaseGeneratedOption.Identity)]attribute. I don't know what's the problem. Does anyone know?!?

我有[System.ComponentModel.DataAnnotations.(DatabaseGeneratedOption.Identity)]属性错误。我不知道有什么问题。有人知道吗?!?

Update

更新

These are the errors:

这些是错误:

The type or namespace name 'DatabaseGeneratedAttribute' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'DatabaseGenerated' could not be found (are you missing a using directive or an assembly reference?)

找不到类型或命名空间名称“DatabaseGeneratedAttribute”(您是否缺少 using 指令或程序集引用?)

找不到类型或命名空间名称“DatabaseGenerated”(您是否缺少 using 指令或程序集引用?)

采纳答案by Erik Funkenbusch

DatabaseGeneratedAttributeis in the System.ComponentModel.DataAnnotations.Schemanamespace attribute in .NET 4.5

DatabaseGeneratedAttributeSystem.ComponentModel.DataAnnotations.Schema位于 .NET 4.5的 命名空间属性中

回答by Mahmoodvcs

If you want to use this attribute in .net 4 you can use Prerelease version of EntityFramework 6 (or even Nightly Builds) to do this, in Manage NuGet Pakageswindow, from the drop-down on top of the window, select Include Prerelease.

如果你想在 .net 4 中使用这个属性,你可以使用 EntityFramework 6 的 Prerelease 版本(甚至 Nightly Builds)来做到这一点,在Manage NuGet Pakages窗口中,从窗口顶部的下拉菜单中,选择Include Prerelease

To update to Nightly Builds, in Pakage Manager Settingsadd this Package Source:

要更新到 Nightly Builds,请Pakage Manager Settings添加此包源:

http://www.myget.org/F/aspnetwebstacknightly/

For a complete guide, see EF on GitHub.

有关完整指南,请参阅GitHub 上的 EF

回答by d4c0d312

You need - in some cases - to change the framework from 4.5 or less to 4.5.1 and then install Entity Framework 6 + and it will be found

您需要 - 在某些情况下 - 将框架从 4.5 或更低版本更改为 4.5.1,然后安装 Entity Framework 6 +,它将被找到