ADO.Net EF - 如何在模型第一方法中定义外键关系? [英] ADO.Net EF - how to define foreign key relation in model first approach?

查看:423
本文介绍了ADO.Net EF - 如何在模型第一方法中定义外键关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直以来有关于类继承的问题,并围绕这个结构化数据库,并使用实体框架没有成功。所以我试图在visual studio中创建实体,看看它自动创建什么数据库表。

I have been having previous issues regards to class inheritance and structuring a database around this and using the entity framework to no success. So I have tried to create the entities inside visual studio and see what database tables it creates automatically.

我有一个Entity MediaItem,它是抽象和游戏的继承者。游戏有一个控制台(Int),对应于ConsoleID。但是,当我生成数据库时,我在MediaItems_Game表中得到一个额外的不需要的列(ConsoleTypes_ConsoleID)。为什么这是,我如何可以防止这种情况发生?感谢。

I have a Entity MediaItem which is Abstract and Game Inherits from this. Game has a Console (Int) which corresponds to ConsoleID. However, when I generate the database I get an extra unwanted column (ConsoleTypes_ConsoleID) inside MediaItems_Game table. Why is this and how can I prevent this from happening? Thanks.

>

推荐答案

首先你的模型可能是错误的。 ConsoleType 游戏不是一对一的关系(除非每个控制台类型都有单一游戏)。我期望1控制台可以有多个游戏。所以它应该是一对多。在现实中,游戏可以在多个平台上发布,所以它应该是多对多的。

First of all your model is probably wrong. ConsoleType and Game is not in one-to-one relation (unless you have single game for each console type). I expect 1 console can have multiple games. So it should be one-to-many. In reality game can be released on multiple platforms so it should be many-to-many.

您有无关的列,因为 ConsoleType 游戏不知道应该使用 Console 属性作为外键。如果您使用独立关联,则会发生这种情况。当您在实体设计器中将它们从一个实体绘制到其他实体时,默认使用独立关联。

You got unvanted column because your relation between ConsoleType and Game doesn't know that it should use Console property as a foreign key. This happens if you use independent association. Independent associations are used by default when you draw them from one entity to other entity in Entity designer. You must use foreign key association.

ConsoleType 到<$ c $绘制关联c> Game - 您必须具有一对多关系):

Start with this set up (draw association from ConsoleType to Game - you must have one-to-many relation):

选择 ConsoleType 游戏在属性中点击参考约束

参考约束对话框只需设置关系:

In Referential Constraint dialog just set up relation:

保存您的模型并再次生成数据库。

Save your model and generate database again.

这篇关于ADO.Net EF - 如何在模型第一方法中定义外键关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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