I’d like to add a new constructor to one of my LTS objects inside a partial class. It should return an instance of the object from the database. Basically the idea is
public Questionnaire(int id)
{
this = (from q in db.Questionnaires
where q.Id == id
select q).SingleOrDefault();
}
I can go through each property and set it to that of the returned object but that seems like overkill and if I change my database model I will have to ensure I edit this code.
So what’s the best practice for doing this? I can’t go for a static method because the DataContext will not be able to track any changes I make to the object.
Would I have to create a new instance of the class, then call a GET method on that class? i.e.
public Questionnaire Get(int id)
{
return (from q in db.Questionnaires
where q.Id == id
select q).SingleOrDefault();
}
Then use it
Questionnaire qs = new Questionnaire();
qs = qs.Get(1);
You may try to follow the implementation suggested by Mike Hadlow in his blog post.
Basically what you’ll be doing is implement that retrieval logic (and other operations) in a class that acts as the repository for a specific kind of objects (in your case – Questionnaire).
It will be something like the following