EF的代码优先,如何在不设置数据库表之间外键的情况下定义导航属性关系 [英] Code first of EF, how to define navigation property relationship without setting foreign key between table in database

查看:346
本文介绍了EF的代码优先,如何在不设置数据库表之间外键的情况下定义导航属性关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用Entity框架的代码。有两个类问题和用户。我定义了如下关系:

I use code first of Entity framework. There are two classes "Question" and "User". I defined a relationship as below:

this.HasRequired(v => v.Creator).WithMany(v => v.Questiones)
.HasForeignKey(v => v.CreatorId).WillCascadeOnDelete(false);

在整理数据库之后,我发现它总是在User的Id和Question的CreatorId之间创建外键。由于FK的性能较低(和其他原因),我想在不设置数据库外键的情况下定义导航属性关系吗? EF创建后要删除FK吗?
如果不能使用流利的api做到这一点,您能告诉我为什么EF以这种方式设计吗?

After gernerating the database I found that it always create foreign key between Id of User and CreatorId of Question. Because of lower performance of FK(and other reason),I want to define navigation property relationship without setting foreign key in database? Delete FK after EF created it? If cannot do this using fluent api, could you tell me why EF designed in this way please?

关于FK的性能较低。我有一个用户表,其中有500万条记录。当我将一个Question插入db时,由于db从User表中检查了question.CreatorId验证,因此它总是比没有FK时慢。
还有很多其他需要删除FK的原因。

About the lower performance of FK. I have a User table with 5 Million records in it. when I insert a Question into db, since the db check the question.CreatorId validation from User table, it always slower than without FK. And there are many other reasons that I need to remove FK.

我认为我有些执着,因为我认为创建FK后删除FK很奇怪,并且丑陋。我想要的是通过在流畅的api中使用诸如WithoutForeignKey之类的方法来实现此目的:

I think I am somewhat obsession because I think that deleting FK after created it is strangely and ugly. What i want is implementing this by using something like WithoutForeignKey in fluent api:

this.HasRequired(v => v.Creator).WithMany(v => v.Questiones)
.WithoutForeignKey(v => v.CreatorId).WillCascadeOnDelete(false); 


推荐答案

毫无疑问,您为什么要尝试做这个奇怪的事情并给出答案:您可以在生成后删除fk约束,也可以使用迁移并从迁移代码中删除FK生成。

Without questioning why are you trying to do this strange thing and going just to the answer: you could delete fk constraint after generated, or you could use migrations and remove FK generation from the migration code.

遍历导航时生成的SQL代码即使不存在fk约束,属性也将起作用,除了级联删除

SQL code generated when traversing nav properties will work even if fk constraint doesn't exist, except for cascade deleting

这篇关于EF的代码优先,如何在不设置数据库表之间外键的情况下定义导航属性关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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