Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to implement Save Operation(Insert/Update) as follow:

Emp n = new Emp();
n.Srl=1;
n.Name = "Mathew";
n.Save();

I should pass entity as the parameter to save Function and it's run correctly but really Ugly!!!... example: n.Save(n)

Model Class :

public class Emp :Classes.Repository<Emp>
   {
       private int srl;
       public int Srl
       {
           set { srl = value; }
           get { return srl; }
       }

       private string name;
       public string Name
       {
           set { name = value; }
           get { return name; }
       }

   }


public class Repository<T> : IRepository<T> where T : class
  {
      public SDataAccess Conn { get; private set; }
      public void Save(T entity)
      {
          if (entity == null)
          {
              throw new ArgumentNullException("entity", "Add to DB null entity");
          }
          //extention Methods
          var res = Conn.Save(entity);
      }

      public IEnumerable<T> GetAll()
      {
          throw new NotImplementedException();
      }



  }


What I have tried:

I implement Save Function in DAL Library as Follow way :

for Example :
Emp a = new Emp();
when calling New Keyword, I call Insert Function else Update Function
and correctly Run.
Posted
Updated 8-Jun-18 2:22am
v3
Comments
Maciej Los 13-Jun-18 7:48am    
Because Repository is type of Emp, you can use something like:
  public void Save()
  {
      if (this == null)
      {
          throw new NullReferenceException("Add to DB null entity");
      }
	  else
	  {
	  		Console.WriteLine("save action!");
	  }
  }

But, the first if statement will never reached if you'll try to call Save method on not initialized Emp variable. You'll get NullReference exception:

Emp m = null;
m.Save(); //here - NullReferenceException!


On the other hand, Repository should be a collection (or list, or array) of entity.

Finally, i'd strongly recommend to implement 2 different methods for insert and update.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900