违反了多重性约束.关系xxx中的角色xxx的多重度为1或0.1

本文关键字:xxx 角色 关系 约束 多重性 | 更新日期: 2023-09-27 18:03:55

我看到这个问题被问了几次,但我恐怕只是不理解答案。

简而言之,我有一个包含PlayerBaseballStat类型属性的Player。这是1对1的关系。PlayerBaseballStat有一个ICollection<BaseballStat>属性。PlayerBaseballStat和BaseballStat都有PlayerId来加入关系。

 public class Player
    {
        public Player()
        {
            // initialize with empty shell
            PlayerBaseballStat = new PlayerBaseballStat();
        }
        public int PlayerId { get; set; }
//other properties removed for brevity
        public virtual PlayerBaseballStat PlayerBaseballStat { get; set; }
    }
public class PlayerBaseballStat 
    {
        [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int PlayerId { get; set; }
        public virtual Player Player { get; set; }
//other properties removed for brevity
       public virtual ICollection<BaseballStat> BaseballStats { get; set; }
    }
public class BaseballStat : EntityBase
    {
        public int PlayerId { get; set; }
        public virtual Player Player { get; set; }
        public int Year { get; set; }
        [MaxLength(25)]
        [Required]
        public string StatName { get; set; }
        [Required]
        public decimal StatValue { get; set; }

    }

映射是:

  modelBuilder.Entity<Player>()
            .HasOptional(p => p.PlayerBaseballStat);
        modelBuilder.Entity<PlayerBaseballStat>()
          .HasRequired<Player>(x => x.Player);
        modelBuilder.Entity<PlayerBaseballStat>()
            .HasMany(p => p.BaseballStats);
        modelBuilder.Entity<BaseballStat>()
            .HasKey(x => new { x.PlayerId, x.Year, x.StatName });
        modelBuilder.Entity<BaseballStat>()
            .HasRequired(x => x.Player);

数据访问层是模板化的存储库。在读操作中违反了多重约束。

public T Get(Expression<Func<T, bool>> where)
    {
        return dbset.Where(where).FirstOrDefault<T>();
    }

实际读取值为

_playerBaseballStatsRepository.Get(x => x.PlayerId == playerId);

转换成

dataContext.PlayerBaseballStats.FirstOrDefault(x => x.PlayerId == playerId);

我知道我在映射中缺少一些东西,但我似乎无法弄清楚。请帮助。

违反了多重性约束.关系xxx中的角色xxx的多重度为1或0.1

具体是什么代码导致了这个问题?是更新现有实体、插入新实体还是简单地检索特定实体?这将有助于如果你可以张贴一些样例代码太。我用上面提供的模式创建了一个小的演示应用程序(去掉base_stat实体上的EntityBase继承),并完美地执行了以下操作:

var player = new Player()
    {
        PlayerBaseballStat = new PlayerBaseballStat()
        {
            BaseballStats = new Collection<BaseballStat>()
            {
                new BaseballStat()
                { 
                    StatName = "ERA", 
                    StatValue = 1.41M, 
                    Year = 2011
                }                                            
            }
        }
    };
    context.Players.Add(player);
    context.SaveChanges();

可能是你初始化对象的方式

问题是您正在Player构造函数中初始化PlayerBaseballStat。这里也有类似的问题

这个需要删除:

// initialize with empty shell
    PlayerBaseballStat = new PlayerBaseballStat();