EF Code First - How to prevent duplicate column on created table on Table-Per-Hierarchy Mapping

旧街凉风 提交于 2019-12-12 06:29:25

问题


I have entity like below

public abstract class MyBaseClass
{
    public int Id { get; set; }
}

public class MyConcrete : MyBaseClass
{
    public int TemplateName { get; set; }
    public int Total { get; set; }
}

public class MyOtherConcrete : MyBaseClass
{
    public int TemplateName { get; set; }
    public int MyProperty { get; set; }
    public string OtherProperty { get; set; }
}

using default initialization, EF will make table with columns like bellow:

Id
TemplateName
TemplateName1 // <-- this is the problem
Total
MyPorperty
MyOtherProperty

now my question how to configure EF so all the TemplateName property on derived class automatically mapped into TemplateName column without making another column. is it possible to configure it on OnModelCreating method?

EDIT

actually above was simplified version of my problem. i have 10 more entities some property might duplicated everywhere and i don't want to add any abstraction layers.

i have tried manually map the column on the OnModelCreating but having "Each property name in a type must be unique. Property name 'TemplateName' was already defined" exception any idea?

EDIT 2

so, i found here, that said it is impossible to do such thing like above in EF, it is weird for me..


回答1:


Move TemplateName into MyBaseClass to avoid this problem.

If necessary, you can use intermediate base classes to hold properties shared by only a subset of your classes.




回答2:


After searching through the net, so far that was not possible to do that. since i realize that my inheritance tree is wrong.

so in my case, i should change my code to match the EF requirement, it is sound weird.. because in many case ENTITY is a NO NO to change, we usually create an entity that used in multiple project. event we found our entity wrong we won't update it because updating it will require massive change on the other projects.

so far, i think there is no exact answer for my question. will update it soon after EF support it.



来源:https://stackoverflow.com/questions/12363477/ef-code-first-how-to-prevent-duplicate-column-on-created-table-on-table-per-hi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!