views:

115

answers:

1

I have some tables that represent various types. They usually just consist of an ID (int), and a name. Ideally I would have this in an enum. Is there a way to map a table like this onto an enum?

EDIT: How would I handle it if there were extra fields other than an ID and Name?

+1  A: 

If it's just an id and a name, I generally do this:

public enum FootScent : int
{
Unknown = 0,
Mild = 1,
Sweaty =2,
SteppedInSomething = 3
}

and then on the LINQ entity property:

[Column("foot_scent_id", DbType = "Int NOT NULL")]
public FootScent Scent { get; set; }

For lookup tables with columns other than "id" and "name" that are needed, I usually just make a normal LINQ entity for them, though depending on your implementation it would probably be worth caching these to minimize trips to the DB.

Daniel Schaffer
Do you know if it's possible to have a custom class as a column type? For instance, if I had a FootScent class, and then the subclasses FootScentUnknown, FootScentMild, etc?
Jeremy Cantrell
You can, but I believe it's a little more complicated and involves lazy-loading. I'd rather just use the id, and keep a dictionary (Dictionary<Int32, FootScent>) cached. Then you can added a (non-linq) property that just returns the FootScent object based on the FootScentId property (linq)
Daniel Schaffer
How would the caching be implemented? I've never done anything like that. I'm still pretty new to LINQ.
Jeremy Cantrell
I'm assuming you're talking about keeping the cache within the FootScent class as a static variable? I would have to instantiate a data context to retrieve the values? Is there some way I can use the data context instance that was used to retrieve the FootScent instance instead of declaring new one?
Jeremy Cantrell
Not necessarily. If you're caching in a web app, you'd want to use HttpContext.Cache. If you're caching in a client app, then I'd use a static class (name it Cached or something, and you can put anything else you cache in there). Persisting a DataContext in general is not a good idea.
Daniel Schaffer
Thanks. I think this is the approach I'm going to try.
Jeremy Cantrell