我遇到了 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;
但我不知道为什么...