1

When working with an entity, which of the following is recommended? (The following code is in UI Layer. UserManager is in Business Layer)

1-

protected void btnReturn_Click(object sender, EventArgs e)
{
    var user = new User();
    user.Name = txtName.Text;
    user.Address = txtAddress.Text;
    ...
    new UserManager().AddUser(User);
}  

In UserManager:

public void AddUser(User user)  
{
    _repository.Add(user);
    _repository.SaveChanges();
}  

public void DeleteUser(User user)  
{
    _repository.Delete(user);
    _repository.SaveChanges();
}  

2-

protected void btnReturn_Click(object sender, EventArgs e)
{
    new UserManager().AddUser(txtName.Text, txtAddress.Text, ...);
}  

And in UserManager:

public void AddUser(string name, string address,...)  
{
    var user = new User();
    user.Name = name;
    user.Address = address;
    context.Users.Add(user);
    context.SaveChanges();
}  

public void DeleteUser(int userID)  
{
    var user = rep.First(u => u.UserID = userID)
    _repository.Delete(user);
    _repository.SaveChanges();
}  
Cœur
  • 37,241
  • 25
  • 195
  • 267
Kamyar
  • 18,639
  • 9
  • 97
  • 171

3 Answers3

1

Choose the first option. Later, when you find out that you have to add n+1 fields to the user form, you can just update the user class to handle the new data. It is nearly always a pain to add those fields as parameters, as you should update every single call to that method to include those fields, even if only one of the calls would actually need the new fields.

Also, as a rule of thumb, if the number of a method's parameters goes above five, you should consider using an object to pass those parameters.

deltaforce2
  • 583
  • 2
  • 8
  • Thanks. You're right. Using objects seems more reasonable. also check out http://stackoverflow.com/q/2294995/337294 for more information. – Kamyar Jun 07 '11 at 07:47
1

You can add a Service (Facade) layer top of Repository(es), then implement complex methods and simple methods such as CRUD to this layer. With this new layer, you used only one class in UI layer

Flexo
  • 87,323
  • 22
  • 191
  • 272
Arash Karami
  • 632
  • 1
  • 8
  • 19
0

I would go for the first - passing an object. I feel it would be easier to maintain.

Sean
  • 696
  • 2
  • 9
  • 24