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

查看:28
本文介绍了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.

我有一个实体 MediaItem,它是 Abstract 和 Game Inherits 的.游戏有一个对应于 ConsoleID 的 Console (Int).但是,当我生成数据库时,我在 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.

推荐答案

首先,您的模型可能是错误的.ConsoleTypeGame 不是一对一的关系(除非每种游戏机类型都有一个游戏).我希望 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.

你得到了 unvanted 列,因为 ConsoleTypeGame 之间的关系不知道它应该使用 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.

从这个设置开始(从 ConsoleTypeGame 绘制关联——你必须有一对多的关系):

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

选择ConsoleTypeGame 之间的关系,然后在属性中点击Referential Constraint:

Select relation between ConsoleType and Game an in properties click on Referential Constraint:

Referential Constraint对话框中设置关系:

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

Save your model and generate database again.

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

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