0

1 対 1 の関係を設定しようとしていますが、属性を FK として宣言する際に問題が発生しました。ここに投稿された質問のいくつかを既に検索して読んでいますが、私の問題には対処していません。

public class User
{
    [Key]
    public int userId {get;set;}
    [DisplayName("User Name")]
    [Required(ErrorMessage="User name required.")]
    public string username {get;set;}
    [DisplayName("Password")]
    [Required(ErrorMessage="Password required.")]
    [MinLength(6)]
    public string password {get;set;}
    [DisplayName("Email")]
    [Required(ErrorMessage="Email required.")]
    public string email {get;set;}

    public virtual List<RoleDetail> roleDetails { get; set; }
    public virtual Customer customer { get; set; }
}

public class Customer
{
    [Key]
    public int cusomterId { get; set; }
    [DisplayName("First Name")]
    [Required(ErrorMessage="First name required.")]
    public string firstname {get;set;}
    [DisplayName("Last Name")]
    [Required(ErrorMessage="Last name required.")]
    public string lastname {get;set;}
    [ForeignKey("userId")]
    public int userId {get;set;}
}

[ForeignKey] アノテーションを使用すると、このエラーが発生します。そして私はSystem.ComponentModel.DataAnnotationsを使用しています。また、[キー]も正常に動作します。

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

ここで何が欠けていますか?

4

2 に答える 2

5

さらにGoogle検索を行った後、問題は解決しました。[ForeignKey] 注釈がSystem.ComponentModel.DataAnnotations.Schemaにあることがわかりました

VS2012 RC で ForeignKey が認識されない

于 2012-09-17T20:42:55.987 に答える
1

編集

以下の私の答えはEF<5.0の場合は正しいですが、EF>=5.0の場合は間違っています。この場合、@MooCowの答えは正しいものです。


とクラスは両方とも名前空間にあります[KeyAttribute]が、2つの異なるアセンブリにあります。[ForeignKeyAttribute]System.ComponentModel.DataAnnotations

[KeyAttribute]System.ComponentModel.DataAnnotations.dll.NETFrameworkに直接属するアセンブリ内にあります。

ただし、EntityFrameworkNuGetパッケージの一部であるアセンブリ[ForeignKeyAttribute]内にあります。EntityFramework.dll

私の意見では、これは、クラスが配置されているプロジェクト/アセンブリにへの参照がないことを意味するだけEntityFramework.dllです。この参照を追加すると、機能するはずです。

補足として:1対1の関係を定義しようとしている方法は機能しません。別の外部キー列/プロパティを使用することはできません。次のように、主キー自体を外部キー(共有主キーの関連付け)として使用する必要があります。

public class Customer
{
    [Key]
    [ForeignKey("user")]
    public int customerId { get; set; }
    //...
    public User user {get;set;}
}
于 2012-09-16T12:12:14.010 に答える