2014-11-25 86 views
1

我想在我的模型中创建一个列作为唯一键。如何在EF代码中的模型中为列添加唯一键首先

我的代码是:

public class Customer 
{ 
    [Index("abcd",IsUnique = true)] 
    public int CustomerID { get; set; } 
} 

,我使用以下参考资料:

using System.ComponentModel.DataAnnotations; 
using System.ComponentModel.DataAnnotations.Schema; 

不过我得到

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

我失去了什么? 荫提前

+0

已经在使用refrence – Santosh 2014-11-25 09:56:03

+0

但你有这条线在你的代码文件的顶部? – DavidG 2014-11-25 09:56:20

+0

是的,现在更改为代码文件的顶部。仍然不起作用 – Santosh 2014-11-25 09:58:47

回答

2

使用EF 6.1版本

由于重组我的答案。 (道歉,如果缩短的URL现在允许)

在.NET 4.5中的索引属性只有文件(EntityFramework.dll)

该DLL System.ComponentModel.DataAnnotations.Schema不包含在存在索引属性

EntityFramework.dll version 6或后来包含此属性

浏览到文件EntityFramework.dll并添加引用,该错误将消失,代码将编译。

的命名空间System.ComponentModel.DataAnnotations.Schema也是这个EntityFramework.dll

我认为它由微软一个大错误,在.net中,可以纠正部分5

1

你需要确保你已经在您的模型类所在的项目中引用了EntityFramework - 我将模型类从我的MVC网站中移出到单独的DLL中,但我认为这是因为IndexAttribute位于它所在的System.ComponentModel.DataAnnotations.Schema名称空间中System.ComponentMode.DataAnnotations程序集 - 它实际上在EntityFramework程序集中,因此您需要参考。

感谢Animuson指出了这一点。

1
  1. 右键单击项目参考部分

  2. 然后点击添加引用在弹出左侧菜单中选择大会

  3. 检查System.ComponentModel.DataAnnotations DLL

  4. 导入下面的命名空间代码

    using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema;

  5. Install Entity Framework for this project