How to use definitions stored in a DB to definitions in your source code?
I would like to get some ideas how to use definitions which are stored in a DB (which is used by your application) into the source code of the application.
Example:
Database
- Cars
- CarTypeDefinitions
A column of Cars
links by a foreign key to a row in CarTypeDefinitions
, therefore defines the type of the car which is contained in Cars
.
Cars
contains entries like 'Aston Martin DB8', 'Range Rover' and 'Mercedes Actros'.
CarTypeDefinitions
contains entries like 'Sports car', 'SUV' and 'Truck'.
Source code
Now I would like to be able to use these definitions in my source code as well. So somehow we need to create some kind of mapping between a row in the CarTypeDefinitions
table and a (preferably) type-safe implementation in the source code.
One possible implementation
The first thing which comes to my mind (and I am especially looking for other solutions or feedback on this one) would be to create an Enum
ECarTypeDefinitions
.
public enum ECarTypeDefinitions
{
SportsCar = 1,
SUV = 2,
Truck = 3
}
Now that we have a type-safe Enum
we can use it e.g. like this:
public bool IsSportsCar(Car currentCar)
{
return (currentCar.CarType == ECarTypeDefinitions.SportsCar);
}
The contents of that enum would be auto-generated from the contents of the CarTypeDefinitions
table (add two additional columns for name of the enum and its integer value).
This would also work the other way, e.g. generate the content of the CarTypeDefinitions
DB table 开发者_如何学运维from the ECarTypeDefinitions
Enum
.
I'm keen to hear about other ways how to tackle this problem. How have you dealt with this?
I do it the way you have suggested. Some others prefer to combine all constants into a "Lookup" table. You can look at an example of some of the pros and cons here: http://weblogs.foxite.com/andykramek/archive/2009/05/10/8419.aspx
Edit: Here's a thought that may help spark further ideas from you.
Create a class for each Car Type:
public class SportsCarType
{
}
Now add an attribute to CarTypeDefinition:
public class CarTypeDefinition
{
...
public string typeName;
}
Populate the new attribute (for each type you have) using typeof:
...
carTypeDefinition.typeName = typeof(SportsCarType).Name;
...
Finally your new IsSportsCar method:
public bool IsSportsCar(Car currentCar)
{
return (currentCar.CarType.typeName == typeof(SportsCarType).Name);
}
I'm not familiar with Entity Framework so perhaps it has a way to allow this kind of thing to be more cleanly done. Also a little rusty on C#.
精彩评论