LINQ to SQL公共基类
2008-09-04 10:02:00 来源:WEB开发网现在,我们可以通过传递Lambda表达式来调用该方法:
[TestMethod()]
public void UpdateWithAction()
{
LinqSampleDataContext context = new LinqSampleDataContext ();
EmployeeAccessor accessor = new EmployeeAccessor();
Employee employee = context.Employees.Single(e => e.EmployeeID == 1);
accessor.Update(employee, t => { t.FirstName = "First"; t.LastName = "Last"; });
}
遗憾的是,这样的测试用例有时却无法通过,会抛出NotSupportedException异常,异常的信息如下:
An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.
原因何在? 究竟发生了什么? 真正的原因是我们所处理的实体与其他实体之间存在关联。如图1所示:
Figure 1: The entity with association
如果移除Employee表中的所有关系,然后重新生成数据模型,测试就能够通过了。
如何解决这个问题呢?显然,显式地去除表的关联并非解决这一问题的最佳方法。这样会影响整个数据模型。对此,Steve Michelotti提出了一个解决方案,也就是利用partial类,为每个数据实体提供一个Detach方法,用以移除实体间的关系:
public partial class Contact
{
public void Detach()
{
foreach (Address address in this.Addresses)
{
address.Detach();
}
}
}
public partial class Address
{
public void Detach()
{
this._AddressType = default(EntityRef<AddressType>);
this._State = default(EntityRef<State>);
}
}
更多精彩
赞助商链接