我已经看过几次这个问题,但是恐怕我只是不理解答案。
简而言之,我有一个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);
我知道我在映射中遗漏了一些东西,但是我似乎无法弄清楚。请帮忙。
最佳答案
到底是什么代码导致了此问题?是更新现有实体,插入新实体还是只是检索特定实体时?如果您也可以发布一些示例代码,这将有所帮助。我使用上面提供的模式(减去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();
可能是您初始化对象的方式。