.NET中的多态关联

Mat*_*att 6 .net sql linq entities polymorphic-associations

如何在.NET中有效/高效地创建多态关联?

话虽如此,我还有一些更细微的问题,我希望将其作为更广泛答案的一部分.

技术

  • .NET 4.0
  • ASP.NET MVC 3
  • MS SQL 2008
  • C#(最新),
  • ADO.NET实体框架/ LINQ到实体

上下文

我正在开发一个面向消费者的应用程序,包括DAL,业务对象层,服务代理层(用于REST服务),最终包括Web,平板电脑,移动和桌面前端.

该应用程序涉及数百种符合各种分类的产品.此外,产品由各种属性组成,这些属性也可能是其更广泛分类的属性.

例:

"小部件A"和"小部件B"都是红色的,因此它们可以在"红色的东西"下的视图中分组.然而,"小部件A"是玩具车,而"小部件B"是红色自行车,因此尽管它们都是红色物体,但它们是不同类型的物体.因此,它们可以在其他视图中被不同地分组(例如,"自行车",其将显示红色自行车,蓝色自行车等).

目标

创建一个有效的核心和服务层,既响应调用者又易于维护.

我在想做什么

为了轻松管理所有这些不同的属性和关系,我想到构建一个"全局"属性表,其中可以为各种类型的对象记录属性:

GLOBAL_ATTRIBUTES_TABLE

  1. ID (INT)
  2. ObjectType (int) - FK到ObjectTypes表包含类型列表(例如自行车,玩具车等)
  3. ObjectId (int) - 它自己的表中对象的id(例如"Bicycles Table")
  4. AttributeType (int) - FK到AttributeTypes表,其中包含各种类型的属性(例如"颜色","材料","年龄组").
  5. AttributeId (int) - 它自己的表中属性的id(例如"Colors Table")

因此,第3列和第5列(ObjectIdAttributeId)理想情况下将具有与其类型对应的表的动态外键.

我的想法是,这将使搜索更快,模型构造更容易,更简洁(代码方面),更容易添加未来属性和对象类型,维护更容易等.

问题

  1. 这是一个可接受的或好的方法(而不是创建,比如产品表,系列表等,有一英里长的列列表)?

  2. 有没有办法在.NET中完成动态外键/多态关联,只需简单地进行查询,使用结果构建模型,查询该模型等等?

  3. 对于更好的数据架构还有其他建议吗?

Kir*_*rst 2

我有一个ObjectType/AttributeType关系,它定义哪些属性类型适用于哪些对象类型,然后是一个简单的Object/Attribute模型。

这应该是适当抽象的。

Object    -> ObjectType
'bicycle' -> 'vehicle'
'toy car' -> 'toy'

Attribute -> AttributeType
'red'     -> 'colour'
'39'      -> 'age'

ObjectType -> AttributeType
'vehicle' has a 'color'
'toy'     has a 'color'
'person'  has a 'age'
-- etc

Object    ->  Attribute
'bicycle' is 'red'
'toy car' is 'orange'
'Grandma' is '105'
-- etc

-- get the object types that have a color
select name from objectType where objectTypeId in
(select objectTypeId from objectTypeAttributeType where attribute = 'color')

-- get the objects that have a color
select name from object where objectTypeId in
(select objectTypeId from objectTypeAttributeType where attribute = 'color')

-- get the objects that have a color that is red
select name from object join attribute
where attribute.color = 'red'
and objectTypeId in
(select objectTypeId from objectTypeAttributeType where attribute = 'color')
Run Code Online (Sandbox Code Playgroud)