How to design database for 2 very similar entities?
I am u开发者_如何转开发sing linq to sql and I have 2 tables(sedan, suv: they are all same except suv has a height column, everything else is same ) but since they are in different tables and pregenerated classes I have a lot of ifs in my functions.Depending on enum car type I manupulate one or the other. I want to get rid of ifs, how should I design the database or how can I achive eliminating ifs ? like can I use generics?
I would use the same table, but have a nullable height column (mapped to a nullable type in C#). Use another column, say type, to encode the vehicle type (you can use this as a discriminator for your classes). Use a constraint so that when the discriminator shows it is an SUV, the height column is required to be non-null.
Now map the table onto an abstract Car class with subclasses of SUV and Sedan, discriminated by the type column. I'd probably make the height property protected in the Car class and then add a public property in the SUV class that exposes the height property (basically using it as a backing field).
Well...It's like having two tables, one for Mercedes and one for BMW only because BMW has a column in plus. So it's better to have a table Car, and fill that column only for BMW.
Please adjust for you case, and of course your height column will only be filled for SUV.
You could solve it by changing the schema. Combine the two tables into a "car" table and include a column for the type and height.
Another way would be to change the implementation of the Sedan and SUV classes to include class-specific logic. (I would assume each implements a "Car" interface?) That way, you let the specific object figure out what to do rather than the calling class. For example: (sudo code)
Sedan's implementation:
public function climbMountain() {
spinTires();
setSpeed(0);
}
SUV's implementation:
public function climbMountain() {
if (randomNumber == 3) rollOver();
}
精彩评论