MVC 5 无法确定 0..1 到 0..1 关系上关联的主体端

MVC 5 Unable to determine the principal end of an association on 0..1 to 0..1 relationship

我在尝试创建 0..1 到 0..1 的关系时遇到问题 首先在 AspNetUsers table 之间使用代码扩展应用程序用户 class 和 MovieModel。 这种关系的本质是用户可以租借或不租借一部电影,并且 一部电影可以租给一个租用者,也可以不租给一个租用者。每个实体都可以独立存在 当没有电影租借或租借者时,外国字段只是 nulls

我的模特:

public class MovieModel
    {
        [Key]
        public int MovieId { get; set; }

        [Required]
        [StringLength(50)]
        [Column(TypeName="varchar")]
        [Display(Name = "Movie Name")]
        public string MovieName { get; set; }
        [Display(Name = "Release Year")]


        public string RenterId { get; set; }

        [ForeignKey("RenterId")]
        public virtual ApplicationUser Renter { get; set; }

应用程序用户Class

public class ApplicationUser : IdentityUser
{

    public int? MovieId { get; set; }
    [ForeignKey("MovieId")]
    public virtual MovieModel Movie{ get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

逻辑上应该可行。有两个外键。 ApplicationUser class (AspNetUser table) 中的一个外键和 MovieModel

中的一个外键

不知何故,我在添加迁移时遇到了这个错误:Unable to determine the principal end of an association between the types 'VideoLibrary.Models.ApplicationUser' and 'VideoLibrary.Models.MovieModel'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotation

为什么会出现这种错误?我不需要关系中的主要实体。他们都可以独善其身。

提前致谢

EF Code First 支持 1:1 和 1:0..1 关系。也许你应该试试 "one to zero-or-one".

我删除了数据注释并由模型构建器创建了它。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<AllesVersUser>()
        .HasOptional<MovieModel>(l => l.Movie)
        .WithOptionalDependent(c => c.Renter)
        .Map(p => p.MapKey("MovieId"));

    base.OnModelCreating(modelBuilder);
}

在我的解决方案中试过这个,我可以在没有租借者的情况下拥有电影,并且在没有电影的情况下拥有用户。