Marko
Marko

Reputation: 72222

Get Method for LINQ-TO-SQL object

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

Upvotes: 1

Views: 1603

Answers (2)

usr-local-ΕΨΗΕΛΩΝ
usr-local-ΕΨΗΕΛΩΝ

Reputation: 26874

The closest solution to your approach is to use a wrapper class with a constructor that retrieves the Questionnaire instance from DB. I hate such an approach (a DAO would be preferred, exactly like the above mentioned repository).

public class QuestionnaireWrapper: Questionnaire {

    private Questionnaire _q;

    public QuestionnaireWrapper(int id)
    {
        _q = (from q in db.Questionnaires
            where q.Id == id
            select q).SingleOrDefault();
    }

    public new string Name 
    {
        get { return _q.Name; }
        set { _q.Name = value; }
    }

    [Other overrides, all of them]
}

What you tried to achieve (this = ...) is not possible because violates basic programming principles. I used such an approach only once, when I needed to create remotable wrappers (: MarshalByRefObject) for objects that were not remotable. And believe me, that is not a clean approach. Please don't downvote me for bad code when I clearly say that ;-)

Observation no. 2: by reading the second part of your code I found you were close. That's why static methods are for!! :)

public static Questionnaire Get(int id)
{
    return (from q in db.Questionnaires
            where q.Id == id
            select q).SingleOrDefault();
}

then

Questionnaire qs = Questionnaire.Get(1);

Upvotes: 0

foliveira
foliveira

Reputation: 626

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

var rep = new Repository<Questionnaire>(...);

var questionnaire = rep.GetById(1);

Upvotes: 2

Related Questions