在实体框架中的两个类之间创建一对一关系时出错

时间:2019-05-07 19:58:03

标签: asp.net-mvc entity-framework entity-framework-6

我正在尝试在两个类之间创建一对一关系。 1位用户拥有1张个人资料图片,而1张个人资料图片属于1位用户。

代码如下。

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

    public byte [] ImageContentBytes { get; set; }
    public string FileName { get; set; }
    public string UserId { get; set; }
    public string ImagePath { get; set; }
    [InverseProperty("UserImage")]

    public virtual ApplicationUser User { get; set; }
    }


public class ApplicationUser : IdentityUser
{
    public string FullName { get; set; }
    public string Address { get; set; }
    public string Postcode { get; set; }
    public string RoleId { get; set; }
    public IdentityRole Role { get; set; }
    public int CityId { get; set; }
    public ICollection<User_Has_Jobs_Posted> UserJobs { get; set; }
    public City City { get; set; } // Adding relationship to the user.
    public IList<JobPost> jobPosts { get; set; }

    [InverseProperty("User")]

    public virtual UserImage UserImage { get; set; }
        }

错误提示:

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

1 个答案:

答案 0 :(得分:0)

在一对一关系中,一个条目必须依赖于另一个条目,而不是两个条目都彼此依赖。

因此,在您的情况下,ApplicationUser条目本身是有效的,而UserImage则无效。

您可以通过在FK上使用Required属性来解决此问题,如下所示:

[Required]
public virtual ApplicationUser User { get; set; }

或者您可以使用流利的api,并按照以下方式进行操作:

modelBuilder.Entity<ApplicationUser>()
    .HasOptional(f => f.UserImage)
    .WithRequired(s => s.User);