jeudi 14 novembre 2019

Unaccesible property just before database insertion

Hello i have the following problem:

I have a class with an ID field.I want to perform mutable operations over this class while keeping the ID immutable.I want this ID to not get touched by the developer.Moreover, i would like this ID to be set by the database on insertion.

The scenario is the following:

public class Can
{
   public int ID{get;set;}
   public int Amount{get;set} 
   public Can(int amount)
   {
      this.Amount=amount;
   }
   public Can()
   {
   }
}

public (Can,Can) SplitCan(this Can can,int amount)
{
     Can second=new Can(can); //copy all properties except id , id is default
     return (can,second);
}
public void SplitAndInsert(Can can,int amount)
{
    (Can first,Can second) = can.Split(amount);
    this.Database.Update(first); //update the database
    int newEntryId=this.Database.Insert(second); // let database assign identity to entry
    Can secondExtracted=this.Database.Get(newEntryID); //get entry with identity set by the database
}

Is this bad design ? I have only found one partial solution but this requires to create two separate models for the Can? One model without the identity to perform operations before database insertion and another for full constructed cans ?

public class UntrackedCan
{
    public int Amount {get;set;}
    public class UntrackedCan(UntrackedCan can)
    {
       this.Amount=can.Amount;
    }
}
public class Can:UntrackedCan
{
    public int ID{get;set;}
}

public void Split(Can can)
{
    UntrackedCan =new UntrackedCan(can); //copy all properties except id , id is default
    return (can,second);
}

  public void SplitAndInsert(Can can,int amount)
    {
        (Can first,Untracked second) = can.Split(amount);
        this.Database.Update(first); //update the database
        int newEntryId=this.Database.Insert(second); // let database assign identity to entry
        Can secondExtracted=this.Database.Get(newEntryID); //Now the UntrackedCan has id assigned by database so it is retrieved as a Can
    }

Is there any way to do this without 2 models?

Aucun commentaire:

Enregistrer un commentaire