We are using Entity Framework 6.1
in our MVC application, using code-first
and table-per-hierarchy
approach since we are developing from scratch and we think this way is suitable for fast development. But now I have a question: say I have one base class and three sub classes, which look like this:
public class BaseClass
{
public int ID { get; set; }
public string Name { get; set; }
}
public class SubClassOne : BaseClass
{
public double Volume { get; set; }
}
public class SubClassTwo : BaseClass
{
public double Volume { get; set; }
}
public class SubClassThree : BaseClass
{
public int Number { get; set; }
}
When using default settings, EF will create 6 columns for the database table: ID, Name, Volume, Volume1, Number and Discriminater. The Volume column will only be used for SubClassOne and Volume1 will for SubClassTwo, Number only for SubClassThree.
I don't care too much about the "waste" of database row spaces. But here is one thing that's bothering me: if I am a new developer and is now looking at the database directly, the names of "Volume" and "Volume1" confuse me. I know on the code side there is SubClassOne and SubClassTwo and both have a property named "Volume". But I could never know which column is for which class. So my question is, is there any way to instruct Entity Framework (e.g., using attribute) that both SubClassOne.Volume
and SubClassTwo.Volume
are mapped to Volume
column in the database. (another benefit is I reduce one column but that's not my main target).
I guess if I don't use Entity Framework, code-first, or table-per-hierarchy, and design the tables and especially the DAL myself, I can have full control and achieve this. But how about now?
You can use Attribute [Column("Volume1")] and [Column("Volume2")] to both Class, so it can map to related Database Column and You have same Property name "Volume".
public class BaseClass
{
public int ID { get; set; }
public string Name { get; set; }
}
public class SubClassOne : BaseClass
{
[Column("Volume1")]
public double Volume { get; set; }
}
public class SubClassTwo : BaseClass
{
[Column("Volume2")]
public double Volume { get; set; }
}
public class SubClassThree : BaseClass
{
public int Number { get; set; }
}
This works fine.If any doubt then tell me.