【问题标题】:MVC 5 Unable to determine the principal end of an association on 0..1 to 0..1 relationshipMVC 5 无法在 0..1 到 0..1 关系上确定关联的主体端
【发布时间】:2015-04-24 07:30:35
【问题描述】:

我在尝试创建 0..1 到 0..1 的关系时遇到问题 在扩展 applicationuser 类和 MovieModel 的 AspNetUsers 表之间首先使用代码。 关系的本质是用户可以租用或不租用一部电影,并且 电影可以租给一个租客,也可以不租。每个实体都可以独立存在 而当没有电影租借或租借者时,外国领域只是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; }

应用用户类

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 类(AspNetUser 表)中的一个外键和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

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

提前致谢

【问题讨论】:

    标签: entity-framework asp.net-mvc-5 ef-code-first


    【解决方案1】:

    EF Code First 支持 1:1 和 1:0..1 关系。也许您应该尝试“一对零或一”。

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

    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);
    }
    

    在我的解决方案中尝试过,我可以在没有租用者的情况下拥有电影,而在没有电影的情况下拥有用户。

    【讨论】:

    • 谢谢!我终于用你的代码让它工作了,但我不得不删除并重新创建数据库。它帮助我理解 EF 的工作原理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 2020-05-08
    • 1970-01-01
    相关资源
    最近更新 更多