首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MVC 5无法确定0..1到0..1关系上关联的主体端

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

Stack Overflow用户
提问于 2015-04-24 07:30:35
回答 1查看 258关注 0票数 0

我在使用扩展应用程序用户类的AspNetUsers表和MovieModel之间的代码首先创建0..1到0.1之间的关系时遇到了问题。这种关系的本质是用户可以租一部电影,一部电影可以租给一名租者,也可以不租一部电影。每个实体都可以独立存在,当没有电影出租或出租时,外域就是nulls。

我的模特:

代码语言:javascript
复制
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; }

ApplicationUser类

代码语言:javascript
复制
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

为什么我会犯这样的错误?我不需要这段关系中的主要实体。他们俩都能单独站着。

提前感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-24 08:29:34

EF代码首先支持1:1和1:0..1关系。也许你应该试试“一到零或者一”。

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

代码语言:javascript
复制
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);
}

在我的解决方案中尝试了这一点,我可以在没有租用人的情况下拥有电影,也可以让用户不用看电影。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29841320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档