如何在保存poco时自动附加关联?

时间:2011-05-17 11:16:05

标签: entity-framework associations poco

我正在使用EF4并尝试使用POCO并始终保持无知。这种方法没有问题,除了关联。

举一个简单的例子,我有国家和国家有相关的货币。每个国家/地区都有一个关联(FK),它是作为财产设置的货币对象,即:

  public class Currency
  {
    //three-character currency-code
    public virtual string Id { get; set; }
    public virtual string Name { get; set; }
    //There are other primitive properties, but they're not important
  }

  public class Country
  {
    //two-character country-code
    public virtual string Id { get; set; }
    public virtual string Name { get; set; }
    //There are other primitive properties, but they're not important

    //Fixup not shown
    public virtual Currency Currency { get; set;}
  }

我通过POCO创建一个新国家/地区(从MS POCO tt自动生成):

  var currency = currencyRepository.Find("AAA");  //returns POCO for the 'AAA' currency
  var country = new Country { Id = "AA", Name = "AA Test", Currency = currency};

我正在使用UnitOfWork模式来实现数据库更改,方法如下:

  public void RegisterNew(country)
  {
    MyDbContext.Countries.AddObject(country);
  }

但是,当我调用SaveChanges时,EF返回我无法创建Country,因为关联的Currency已经存在(插入Currency失败, PK违规)。

好吧,好吧,但我想将Country与现有的Currency相关联......这就是我给它货币的原因。

我可以将RegisterNew中的代码添加到现有Attach对象的Currency中,但是,我想要一个通用的解决方案。我不想为我想要保留的每个POCO对象编写特定的代码来附加现有的关联。

有没有办法告诉EF如果关联实体已经存在,那么使用它(如果POCO实体与持久性实体不匹配,那么它可能会抛出错误)?

我假设没有。如果不能做到这一点,我将不得不写很多(对我而言)毫无意义的额外代码来说'是的,这是一个现有的关联,显然,使用现有的持久实体),更烦人的是,我从我的角度来看,将无法编写通用代码来添加任何类型的POCO对象,这不是DRY和很多毫无意义的努力。

也许我可以使用外键,但后来我没有关联,它不会是一个与持久性无关的ORM解决方案,而是一个相当重的持久性感知DAL。

1 个答案:

答案 0 :(得分:1)

尝试在Country而不是Currency对象中设置货币ID的原始值。我遇到了类似的问题,这个解决方案适合我!