我看到这个问题被问过几次,但恐怕我只是不理解答案。
简而言之,我有一个包含 PlayerBaseballStat 类型属性的 Player。它是一对一的关系。 PlayerBaseballStat 有一个 ICollection<BaseballStat>
属性(property)。 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);
我知道我在映射中遗漏了一些东西,但我似乎无法弄清楚。请帮忙。
最佳答案
具体是什么代码导致了这个问题?是在更新现有实体、插入新实体还是仅检索特定实体时?如果您也可以发布一些示例代码,那将会有所帮助。我使用上面提供的架构创建了一个小型演示应用程序(减去 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();
这可能是您初始化对象的方式。
关于c# - 违反了多重约束。关系 xxx 的角色 xxx 具有多重性 1 或 0..1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15423713/