违反了多重约束。关系xxx的角色xxx具有多重性1或0..1

时间:2013-03-15 02:28:27

标签: c# entity-framework data-binding

我已经看过几次这个问题,但我担心我只是不理解答案。

简而言之,我有一个包含PlayerBaseballStat类型属性的Player。它是一对一的关系。 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);

我知道我在映射中遗漏了一些内容,但我似乎无法弄明白。请帮忙。

1 个答案:

答案 0 :(得分:1)

具体导致此问题的代码是什么?是在更新现有实体,插入新实体还是只是检索特定实体时?如果您也可以发布一些示例代码,这将有所帮助。我创建了一个带有上面提供的模式的小型演示应用程序(减去BaseballStat实体上的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();

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