Create a new record based on another with Entity

2

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

  • I keep a line of bd in a variable

     Market novo = new market();
     novo = context.Markets.where(blabla).First();
    
  • I change a column of the line

     novo.ParentID = 50;
    
  • I'm trying to get the error message:

     context.AddObject(novo); // da erro por causa da PrimaryKey
    
  • asked by anonymous 19.09.2017 / 15:07

    2 answers

    2

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

    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);
    
        
    19.09.2017 / 15:43
    0

    You can also use MemberWiseClone . This method exists in the Object class but has protected access so if you can use it it can be made available in a method:

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

    And use as follows:

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

    Please note that MemberwiseClone makes a copy of the integral object, ie the references to other objects are retained.

        
    19.09.2017 / 17:41