LoginSignup
4
5

More than 5 years have passed since last update.

code first でカラムにユニーク制約をつける

Posted at

対象のカラムにIndexアノテーションをつけて終了。

/*
using System.ComponentModel.DataAnnotations.Schema;
*/
[Index(IsUnique = true)]
public string Email { get; set }

と思ったら、上記のようにstring型に対してUniqueを設定すると、Databaseマイグレーション時に以下のようなエラーが出る。

Column 'Email' in table 'dbo.Users' is of a type that is invalid for use as a key column in an index.

原因は、SQLServerの index key の最大長が900Byteだからとのこと。
ということで、カラムに最大長を設定してあげることで解決する。
最終的にはこちら。

/*
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
*/
[Index(IsUnique = true)]
[StringLength(256)]
public string Email { get; set }

参考(というかそのまま)
http://stackoverflow.com/questions/10614575/entity-framework-code-first-unique-column

4
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5