EF代码第一个抽象关系? [英] EF Code First abstract relationship?

查看:79
本文介绍了EF代码第一个抽象关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,该类继承与另一个类有关系的基类.

I have a class that inherits a base class to which another class has relationships.

示例:

  • 基类:动物
  • 子类别1:狗
  • 子类别2:猫
  • 相关的一对多表:疫苗接种
    • 狗可以接种多种疫苗.这被实现为List< Vaccination>.
    • 猫可以接种多种疫苗.
    • 疫苗接种记录只能有一只动物与之关联.
    • 疫苗接种不知道它与狗还是猫有关.(狗和猫使用非碰撞GUID.)

    没有动物表;动物是抽象类.但是疫苗接种只知道动物,而不知道狗.(但是,EF对这两者都了解.)我将类库分开,以使Animal和Vaccination在核心库中,而Dog在另一个引用核心库的库中.

    There is no Animal table; Animal is an abstract class. But Vaccination knows only about Animal, not about Dog. (EF, however, knows about both.) I have my class libraries split such that Animal and Vaccination are in a core library and Dog is in another library that references the core library.

    当首先使用Entity Framework Code时,疫苗接种表将获得额外的列:Dog_ID,作为Dog类的List< Vaccination>.显式声明正在创建一个推断.这样,此列将疫苗接种记录映射到狗.没关系,除了我想在多种动物类型之间共享此额外列的事实之外.因此,例如,我不想有一个Dog_ID和Cat_ID,而是想要一个Animal_ID来加入Dog或Cat.

    When using Entity Framework Code First, the Vaccinations table is getting the extra column: Dog_ID, as Dog class's List<Vaccination> explicit declaration is creating an inference. As such, this column maps the vaccination record to the dog. This would be fine, except for the fact that I want to share this extra column across multiple types of Animal. So for example rather than have a Dog_ID and a Cat_ID I'd like to have an Animal_ID that could join to either the Dog or the Cat.

    由于Animal是抽象的并且没有数据库表,我可以用流利的语句和/或property/attribute声明来做到这一点吗?

    As Animal is abstract and has no DB table, can I accomplish this with perhaps a fluent statement and/or property/attribute declarations?

    推荐答案

    除非您创建 Animal ,否则您的疫苗接种表对于每种接种疫苗的动物将始终具有附加的FK列.表并与该表建立关系.EF无法映射和高级抽象的关系-关系必须遵循与直接在数据库中创建关系相同的规则.

    Your Vaccination table will always have additional FK column for each vaccinated type of animals unless you create Animal table and make relation to that table. EF cannot map and high level abstraction of relations - relations must follow same rules as if you create them directly in the database.

    如果仅可以给一些动物接种疫苗,则可以将另一个表添加到层次结构中,并与该新表建立联系(EF无法使用接口).您将需要

    If only some animals can be vaccinated you can add another table to hierarchy and make relation with that new table (EF is not able to work with interfaces). You will need Table per Type mapping for that and it will make performance of your queries much worse in current EF version.

    这篇关于EF代码第一个抽象关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆