一对一,首先是EF代码属性

时间:2013-11-18 13:20:41

标签: entity-framework ef-code-first

我试图将两个模型与一对一关系联系起来 课程如下:

public class Customer : BaseEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    [ForeignKey("Account")]
    public int AccountId { get; set; }

    public virtual Account Account { get; set; }

    [Required(AllowEmptyStrings = false)]
    public string Address { get; set; }

    [Required(AllowEmptyStrings = false)]
    public string PublicName { get; set; }

    [Required]
    public int UserId { get; set; }

    [ForeignKey("Id")]
    [InverseProperty("Customer")]
    public virtual User User { get; set; }

    public virtual ICollection<Project> Projects { get; set; }

}

public class User : BaseEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [MaxLength(32)]
    [RegularExpression(@"^[\w]+(\.?[\w\d_]+)?$")]
    public string Login { get; set; }

    [Required]
    [MinLength(6)]
    [DataType(DataType.Password)]
    [RegularExpression(@"^[\w]+(\.?[\w\d_]+)?$")]
    public string Password { get; set; }

    [Required]
    [StringLength(32)]
    [DataType(DataType.EmailAddress)]
    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")]
    public string Email { get; set; }

    [Required]
    public string Firstname { get; set; }

    [Required]
    public string Lastname { get; set; }

    [MaxLength(256)]
    public string ProfilePhoto { get; set; }

    [Required]
    [ForeignKey("Account")]
    public int AccountId { get; set; }

    [Required]
    public virtual Account Account { get; set; }

    [InverseProperty("User")]
    public virtual ICollection<Rate> Rates { get; set; }

    public int CustomerId { get; set; }

    [ForeignKey("Id")]
    [InverseProperty("User")]
    public virtual Customer Customer { get; set; }

}

我搜索了但没有找到解决方案,而不仅仅是属性。任何人都可以帮助我吗? 提前谢谢!

1 个答案:

答案 0 :(得分:1)

您所犯的错误是您将两个表彼此指向为与另一个表具有外键关系。您必须选择一个表作为基表,而另一个表作为其中包含FK的表。如果您希望User表作为基础,那么您将执行以下操作:

User课程:从[ForeignKey]删除[InverseProperty]Customer属性。

Customer班级:

[Key, ForeignKey("User")]
public int Id { get; set; }

//Other fields

public virtual User User { get; set; }