tags:

views:

46

answers:

2

I have a "Literal" class that defines a text value and an ID. I want to build a static method that is simply "FromValue(string)" within the Literal class (LINQ to SQL), so that it'll return the proper Literal instance from a given value.

I'm having some trouble figuring out how to do this, though. I mean, I can call it in code everytime I need it, but it would be much more convenient and time saving to just wrap it into the class itself.

Any ideas?

using System;
using System.Linq;

namespace Context
{
    public partial class Literal
    {
     public static Literal FromValue(string value)
     {
      // linq code, how do I reference the existing data context?
      return null;
     }
    }
}
+1  A: 

What "existing data context"? There may well be more than one data context alive at the point of the call to FromValue, e.g.:

using (FooDataContext ctx1 = new FooDataContext())
using (FooDataContext ctx2 = new FooDataContext())
{
    Literal.FromValue(...); // which one?
}

You'll have to pass it as parameter, there really isn't any better way.

Also note that you won't be able to use FromLiteral in your LINQ2SQL queries (since the query parser and translator has no idea what it does).

Pavel Minaev
If he needs to use FromLiteral() from linq2sql queries, he could have it return an IQueryable. I agree thought he best thing is to just take the DataContext as an input parameter.
Frank Schwieterman
Mostly trying to make it more simple for assignment, rather than actual query. I can query by the name easily enough. Just trying to avoid making a new object, running a query, and then assigning it everytime the literal needs to be assigned to something.
Stacey
What I means is using `FromLiteral()` in a `select`. It won't work no matter what.
Pavel Minaev
No, this isn't intended to be used during a select.
Stacey
A: 

Right, well, the "FromLiteral" is what I'm using to assign it to a Key that it is attached to. Like this...

unit.Ring.Keys.Add(new Key(Literal.FromValue("Name",database), item[0]));

Where 'database' is the instance of the datacontext. I just wanted to see if there was a better way to do it. I want to assign them by string value, you see, I don't know the ID as is proper.

Stacey