arame3333
arame3333

Reputation: 10203

C# Using an ID to create an object in a constructor

I want to create an Employee object using the constructor;

public Employee(int _employeeId)

In the body I want to read an employee from the database. However I cannot get away with;

using (SHPContainerEntities db = new SHPContainerEntities())
{
    this = db.Employee.Where(x =>x.EmployeeId == _employeeId).SingleOrDefault() as Employee;
}

Because "this" is readonly. So how do I do this?

Upvotes: 1

Views: 327

Answers (5)

Ashok
Ashok

Reputation: 51

Humm...

'this' is a reference to your current object instance. While in the ctor, you're in the process of creating and constructing the object itself. You can't change your reference inside the ctor and assign into your self which is fundamental reason of not allowing to change it or read-only.

The factory pattern mentioned by others are the solution for this.

HTH

Upvotes: 0

Mikael
Mikael

Reputation: 453

As pointed out you cannot set ”this” as it is read only (for a good reason). In your case the object is already created when the constructor executes, which means that you cannot change the type of the object. What you could look into (and what is already proposed) is to have a static method which creates the class for you. Look up the “Factory” design pattern, e.g. http://en.wikipedia.org/wiki/Factory_method_pattern

Upvotes: 2

Kamyar
Kamyar

Reputation: 18797

You have to change your coding style. you ave to get the employee from somewhere else. for example, Try to use the Repository pattern:

var employee = EmployeeRepository.GetEmployee(emplieeID);  

Upvotes: 1

Peter van Kekem
Peter van Kekem

Reputation: 1447

You can do this in another class, that actually makes the Employee object.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063619

You could just re-write it as a static method:

public static Employee Get(int id) {
    return db.Employee.SingleOrDefault(x => x.EmployeeID == id);
}

(note: the above is just for illustration; there are real problems associated with a static data-context (db) - don't do that! It should really use a GetContext() method or similar, that worries about that)

Upvotes: 4

Related Questions