开发者

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. How开发者_如何学Pythonever 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?


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)


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


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);  


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜