2

Unable to determine the principal end of an association between the types 'XYZ.Models.Attachment' and 'XYZ.Models.Accounts.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

Exception has been thrown by the target of an invocation.

That error I get, when I try to update-database with my EF Models.

Part of User.cs:

[Table("Users")]
public class User
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    public int MainPhotoId { get; set; }

    [ForeignKey("MainPhotoId")]
    public virtual Attachment Photo { get; set; }
}

Attachment.cs

[Table("Attachments")]
public class Attachment
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int AttachmentId { get; set; }

    public string name { get; set; }


    public int UserId { get; set; }
    public DateTime AddDate { get; set; }

    public bool del { get; set; }

    [ForeignKey("UserId")]
    public virtual User Author { get; set; }

}

Why I get this error? And how to resolve it?

Regards

4

1 回答 1

1

映射约定检测和之间的一对一关系,User.Photo并且Attachment.Author不能推断主体和从属端是什么。因此例外。

实际上,根据您的评论,您想要两个关系而不是一个一对一的关系。您只能通过使用 Fluent API 覆盖约定来实现这一点,并且您可能需要将其中一种关系设为可选User,否则您将在和之间存在循环相互依赖关系Attachment。例如,您可以User.Photo通过选择可为空的外键来使该属性成为可选:

public int? MainPhotoId { get; set; }

然后映射将如下所示:

modelBuilder.Entity<User>()
    .HasOptional(u => u.Photo)
    .WithMany()
    .HasForeignKey(u => u.MainPhotoId);

modelBuilder.Entity<Attachment>()
    .HasRequired(a => a.Author)
    .WithMany()
    .HasForeignKey(a => a.UserId);

使用此映射,您可以删除[ForeignKey]属性,因为 FK 属性的定义是 Fluent API 映射 ( HasForeignKey) 的一部分。

于 2013-09-22T12:53:39.260 回答