我看到这个问题被问了几次,但我恐怕没有理解答案。
简而言之,我有一个包含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);
我知道映射中缺少了什么,但似乎无法弄清楚。请帮忙。