Create a new record based on another with Entity

Asked

Viewed 74 times

2

I need to add some columns to a database as follows:

  1. save a comic line to a variable

     Market novo = new market();
     novo = context.Markets.where(blabla).First();
    
  2. change a row column

     novo.ParentID = 50;
    
  3. I save the line in BD, but it is an error because the key of the line I am adding already exists and I do not know how to reset this key in my code.

     context.AddObject(novo); // da erro por causa da PrimaryKey
    
  • 1

    you just have to change the record, and not add a new one, the error there is only in your logic... and, I think it’s not ADO.NET

  • There’s no mistake, that’s the point. This table is a tree with hierarchies, what ueu want to do is search a sub-category(line), just change Parentid and add it in the comic again, but now it will belong to another parent category

2 answers

2

If the need is to create a new object then what you should do is copy the properties of the base object and not assign the object completely, thus:

Market novo = new market();
var objAux = context.Markets.where(blabla).First();

novo.prop1 = objAux.prop1;
novo.prop2 = objAux.prop2;
novo.prop3 = objAux.prop3;
novo.prop4 = NovoValor;

context.AddObject(novo);
  • The goal is to include a new object because of the changed column. I need to have both in the database, the original + changed

  • I modified the answer to this need. Adapt to your code.

  • Okay, I wanted to avoid doing that but it’s gonna have to be

  • Object orientation is like this, if you assign one object to the other it will assign by reference and not by value. In some languages this can be specified, in others this is automatic.

0

You can also make use of MemberWiseClone. This method exists in the class Object but you have access protected so if it is useful you can make it available in a method:

public Market Clone(){
    return base.MemberwiseClone() as Market;
}

And use as follows:

var objAux = context.Markets.where(blabla).First().Clone();

Keep in mind that the MemberwiseClone makes a copy of the integral object, ie references to other objects are maintained.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.