我见过这个问题问了几次,但恐怕我只是不理解答案。
简而言之,我有一个 Player,其中包含 PlayerBaseballStat 类型的属性。它是一对一的关系。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);
我知道我在映射中遗漏了一些东西,但我似乎无法弄清楚。请帮忙。