当添加子节点时,多对多不更新数据库
本文关键字:更新 数据库 添加 子节点 | 更新日期: 2023-09-27 18:06:16
考虑以下模型/映射
[DataContract]
public class CustomPhrase : ModelBase
{
private ICollection<EnglishPhrase> translations;
public CustomPhrase()
{
this.translations = new List<EnglishPhrase>();
}
[DataMember]
public virtual string Phrase { get; set; }
[DataMember]
public virtual IEnumerable<EnglishPhrase> Translations
{
get
{
return this.translations;
}
}
}
[DataContract]
public class EnglishPhrase : ModelBase
{
private ICollection<CustomPhrase> translations;
public CustomPhrase()
{
this.translations = new List<CustomPhrase>();
}
[DataMember]
public virtual string Phrase { get; set; }
[DataMember]
public virtual IEnumerable<CustomPhrase> Translations
{
get
{
return this.translations;
}
}
}
public CustomPhraseMap() : base("Translation_CustomPhrase", "CustomPhraseId")
{
this.Property(x => x.Phrase);
this.Set(
x => x.Translations,
map =>
{
map.Table("Translation_Link");
map.Key(key => key.Column("CustomPhraseId"));
map.Access(Accessor.Field);
map.Cascade(Cascade.All);
},
map => map.ManyToMany(c => c.Column("EnglishPhraseId"))
);
}
public EnglishPhraseMap() : base("Translation_EnglishPhrase", "EnglishPhraseId")
{
this.Property(x => x.Phrase);
this.Set(
x => x.Translations,
map =>
{
map.Table("Translation_Link");
map.Key(key => key.Column("EnglishPhraseId"));
map.Access(Accessor.Field);
map.Cascade(Cascade.All);
},
map => map.ManyToMany(c => c.Column("CustomPhraseId"))
);
}
如果我执行这段代码,实体被添加到数据库中,但链接表Translation_Link
没有更新。
var customPhrase = new CustomPhrase { Phrase = "Gobble" };
var englishPhrase = new EnglishPhrase { Phrase = "Hello" };
customPhrase.AddTranslation(englishPhrase);
this.customPhraseRepository.Add(customPhrase);
我不确定这是映射问题,还是存储库配置问题。也许我在错误的时间添加了孩子??
有其他人以前遇到过这个问题并能够解决它吗?
需要将两边的集合的逆设置为TRUE
我设法使用事务解决了这个问题。
try
{
unitOfWork.BeginTransaction();
var custom = this.customPhraseRepository.FindCustomPhraseByPhrase(customPhrase);
if (custom == null)
{
custom = new CustomPhrase() { Phrase = customPhrase };
this.customPhraseRepository.Add(custom);
}
var english = this.englishPhraseRepository.FindEnglishPhraseByPhrase(englishPhrase);
if (english == null)
{
english = new EnglishPhrase() { Phrase = englishPhrase };
this.englishPhraseRepository.Add(english);
}
custom.AddTranslation(english);
this.customPhraseRepository.Update(custom);
unitOfWork.EndTransaction();
}
catch (Exception)
{
unitOfWork.RollBack();
}
finally
{
unitOfWork.Dispose();
}