NotSupportedException で問題が発生しました。「別の DataContext からロードされた可能性がある、新しくないエンティティをアタッチまたは追加しようとしました。」
partial class SupplyOfert : Model
{
public SupplyOfert(int id = 0)
{
if (id > 0)
this.get(id);
}
public Supplier supplier
{
get
{
return this.Supplier;
}
set
{
this.Supplier = db.Suppliers.SingleOrDefault(s => s.id == value.id);
}
}
public override bool get(int id)
{
SupplyOfert so = (SupplyOfert)db.SupplyOferts.SingleOrDefault(s => s.id == id).Copy(this, "Supplies");
this._Supplies = so._Supplies;
so._Supplies.Clear();
if (this.id > 0)
{
db.Dispose();
db = new Database();
db.SupplyOferts.Attach(this); // here I'm getting the exception
return true;
}
else
return false;
}
public override void save()
{
if (this.id <= 0)
db.SupplyOferts.InsertOnSubmit(this);
db.SubmitChanges();
}
public override void remove()
{
if (this.id > 0)
{
db.SupplyOferts.DeleteOnSubmit(this);
db.SubmitChanges();
}
}
}
次の方法で新しいレコードを追加すると:
SupplyOfert ofert = new SupplyOfert();
ofert.price = 100;
ofert.publisher = "some publisher";
ofert.supplier = new Supplier(1);
ofert.title = "some title";
ofert.year = DateTime.Today;
ofert.save();
大丈夫ですが、レコードを更新したいときは、次を使用します。
SupplyOfert ofert = new SupplyOfert(2);
ofert.price = 220;
ofert.publisher = "new publisher";
ofert.save();
「NotSupportedExceptionw が処理されませんでした」というメッセージが表示されます。
モデルクラスは次のとおりです。
public abstract class Model
{
protected Database db = new Database();
public Model(){}
~Model()
{
db.Dispose();
}
abstract public bool get(int id);
abstract public void save();
abstract public void remove();
}
そして、ここにコピー方法があります:
public static class ObjectProperties
{
public static object Copy(this object source, object destination, string skip = "")
{
if (source != null)
{
foreach (var sourceProperty in source.GetType().GetProperties())
{
foreach (var destinationProperty in destination.GetType().GetProperties())
{
if (destinationProperty.Name == sourceProperty.Name && destinationProperty.Name != skip)
destinationProperty.GetSetMethod().Invoke(destination, new object[] { sourceProperty.GetGetMethod().Invoke(source, null) });
}
}
}
else
destination = null;
return source;
}
}
データベースクラスは次のとおりです。
public class Database : DataClasses1DataContext
この問題は割り当てに関連していることがわかりました:
this.supplier = so.supplier;
しかし、なぜだかわかりません...