【发布时间】:2016-01-23 23:09:01
【问题描述】:
我有一个使用复合键作为 PK 的实体。我想将QuestStage 的集合添加到自身,但是在映射键时,实体框架告诉我该键已被使用。处理这种情况的最佳方法是什么?我需要两个密钥来共享QuestID,因为两个QuestStages 都属于一个Quest
实体 - PK(QuestID、阶段)
public class QuestStage
{
public QuestStage
{
FollowUpQuestStages = new List<QuestStage>();
}
public int QuestID { get; set; }
public int Stage { get; set; }
public virtual ICollection<QuestStage> FollowUpQuestStages { get; set; }
}
映射
public class QuestStageMap : EntityTypeConfiguration<QuestStage>
{
public QuestStageMap()
{
// Non Problematic Mappings
// Problematic Mapping
HasMany(x => x.FollowUpQuestStages)
.WithMany()
.Map(m =>
{
m.ToTable("FollowUpQuestStage");
m.MapLeftKey("QuestID", "StageID");
m.MapRightKey("QuestID", "FollowUpStageID");
});
}
}
【问题讨论】:
-
通过您的示例,我假设您使用的是“代码优先”方法。这样做时您是否尝试过“数据库优先”?
-
是的,我首先使用代码。我没有先尝试过数据库,但我可以尝试一下,看看它为我生成了什么。
-
这将是我的第一次尝试——主要是因为 SQL 是我比 EF 更好的朋友。 ;)
标签: c# sql .net database entity-framework