Home > Software design >  How to solve the proble,
How to solve the proble,

Time:08-16

hey i have a small time tracking programm and i got problems with me delete task for the Users.

i got a usertasks class with several tasks.

Action<object> DeleteUserAction = (object obj) =>
{
    Type type = typeof(DatabaseContext);
    FieldInfo fieldInfo = type.GetField("Users");
    obj = new DatabaseContext();
    DatabaseContext context_ = (DatabaseContext)obj;

    context_.Users.Remove(context_.Users.Single(u => u.ID == _id));
    context_.SaveChanges();
};

public void DeleteUser()
{
    dbController.RunTaskByAction(DeleteUserAction);
}

the Action goes to my DbController class. The DBController class is just for actions. he is just working with the actions from my classes.

public void RunTaskByAction(Action<object> action_)
{
    Task t1 = new Task(action_, "DatabaseContext");
    t1.Start();

    Task t2 = new Task(action_,"DatabaseContext");
    t2.Start();

    Task t3 = new Task(action_, "DatabaseContext");
    t3.Start();

    Task t4 = new Task(action_, "DatabaseContext");
    t4.Start();

}

After that i want to carry out that method after a buttonclick in my gui

 private void btnDelete_Click(object sender, EventArgs e)
    {
        Tasks.MitarbeiterTasks MTasks = new Tasks.MitarbeiterTasks(context, dBController);
        MTasks.DeleteUser();
    }

the problem is the _id

 context_.Users.Remove(context_.Users.Single(u => u.ID == _id));

CodePudding user response:

It seems you are complicating this more than necessary. I'm unsure why you create it as a Action<> rather than a normal method, but if we stick with that, you can simplify your action like this:

Action<int> DeleteUserAction = (int userId)=>
{
    var context = new DatabaseContext();
    var entity = context.Attach(new User { ID = userId });
    entity.State = EntityState.Deleted;
    context.SaveChanges();
};


public void DeleteUser()
{
    // Not sure where the ID should come from, but I guess you know
    int userIdToDelete = /*...*/;

    dbController.RunTaskByAction(() => DeleteUserAction(userIdToDelete));
}

// Remove the '<object>' type parameter from the Action
public void RunTaskByAction(Action action_)
{
    // ...
}
  • Related