Vitaliy、申し訳ありませんが、そのブログ投稿を失いました。それでもコードは持っています。
public class EntityBase : IEntityBase
{
/// <summary>
/// Detaches the entity, so it can be added to another dataContext. It does this by setting
/// all the FK properties to null/default.
/// </summary>
public void Detach()
{
// I modified the .tt file to generate the Initialize method by default.
// The call to OnCreated() is moved to the constructor.
GetType().GetMethod("Initialize", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);
}
}
そして、これが私のアダプターからの Detach() への呼び出しです
public class OrderAdapter : IOrderAdapter
{
public void Add(IOrder order)
{
try
{
using (var db = new ATPDataContext())
{
Order newOrder = (Order)order;
newOrder.Detach(); // not required for insertion, but to keep references to Product
db.Orders.InsertOnSubmit(newOrder);
db.SubmitChanges();
}
}
catch (Exception ex)
{
}
}
}
そして、私の .tt ファイルで
#region Construction
public <#=class1.Name#>()
{
Initialize();
<# if (class1.HasPrimaryKey) {#>
OnCreated();
<# } #>
}
private void Initialize()
{
<# foreach(Association association in class1.Associations) { #>
<#=association.Storage#> = <#
if (association.IsMany) {
#>new EntitySet<<#=association.Type.Name#>>(attach_<#=association.Member#>, detach_<#=association.Member#>);
<# } else {
#>default(EntityRef<<#=association.Type.Name#>>);
<# }
}
#>
}
#endregion
チッ!