2

考虑以下模型/映射

[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);

我不确定这是映射问题还是存储库配置问题。也许我在错误的时间添加了孩子?

以前有没有其他人遇到过这个问题并能够解决它?

4

2 回答 2

1

对于两边的集合,您需要将逆向设置为 TRUE。

于 2011-08-20T09:40:12.540 回答
1

我设法使用事务解决了这个问题。

  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();
  }
于 2011-08-23T18:39:06.803 回答