开发者

increasing object numbers in db4o

I would like to ask you about a problem that I have. I use ASP.NET as an interface and db4o as database. I have this class structure:

  • Prj(Class) (Eqp is an attribute of Prj)
    • ...Eqp(Class) (the attributes of Eqp are these two:)
      • ..EqpSpec(Class)
      • ..Job(attribute)

My code is below, and I don't understand why after I stored i开发者_如何学JAVAt the objects in EqpSpec increased.

If I have an "a" object after I closed the program and reopen it I get two from the drop down list. (I choose EqpSpecName from the dropdownlist(ddlEqp) which I stored the objects before in it and I write the Job to TxtJob and I first store it to array in the AddEqp. And then I take it from the session and store it to the database in the Update_Click.)

 /* I use this method to add */
protected void AddEqp_Click(object sender, EventArgs e)
{  
     // ...

     EqpSpec objEqpS = new EqpSpec();
     objEqpS.EqpName = ddlEqp.SelectedValue;
     objEq.EqpSpec = (EqpSpec)db.Next(objEqpS);
     objEq.Job = Convert.ToInt32(TxtJob.Text);
     listEqp.Add(objEq);
     Session["listEqp"] = listEqp;
}

 /*  I use this method for both update and store */
protected void Update_Click(object sender, EventArgs e)
{
    DatabaseConnection db = new DatabaseConnection();
    ArrayList listEqp = (ArrayList)Session["listEqp"];
    Prj objPrj= new Prj();
    objPrj.PrjName = ddlPrj.SelectedValue;
    objPrj = (Prj)db.Next(objPrj);      
    Eqp[] arrayEqp = new Eqp[listEqp.Count];
    for (int i = 0; i < listEqp.Count; i++)
       arrayEqp = (Eqp)listEqp;
    objPrj.Eqp = arrayEqp;
    db.Update(objPrj);
}

What is the reason for the duplication, and how can I avoid it?


It sounds like you are creating duplicate objects in your db. This is a common problem (even more common in web scenarios).

The first thing to understand is that object identity in db has nothing to do with object properties and values. So even though you create an object with the same values, either via new, clone, deserialization etc. it is not the same object as the original. Storing this object will create "duplicates" in your db.

The way db4o deals with identity is it keeps track (references) of objects. This is only possible if your db4o object container is open and you are within its context. Closing object container, moving objects outside the scope of your app etc. will result in db4o losing track of that object.

There are two common ways of dealing with this problem: a) Whenever you need to update an object you load the object from db, change it's value and store it back. b) Use Bind method to tell db4o your current object is the same as the object you wish to update in your db.

For more specific advice you'd need to share more info about your application and what exactly you wish to achieve.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜