[英]How to prevent Entity Framework foreign key generation?
I have an Item
class with a RelatedItemId
property.我有一个带有
RelatedItemId
属性的Item
类。 RelatedItemId
can reference another Item
that does not yet exist in the database. RelatedItemId
可以引用数据库中尚不存在的另一个Item
。
In this case, I want item.RelatedItem == null
.在这种情况下,我想要
item.RelatedItem == null
。
How to tell EF to not create a foreign key for this field?如何告诉 EF 不为此字段创建外键?
public class Item
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public Guid? RelatedItemId { get; set; }
public Item RelatedItem { get; set; }
}
Now Entity Framework generates foreign key I don't need:现在实体框架生成我不需要的外键:
I'm looking way to have it like this:我正在寻找这样的方法:
I tried to ask for clarification via Comment, but I don't yet have enough Reputation Points.我试图通过评论要求澄清,但我还没有足够的声望点。 So I'll give an answer that includes some assumptions about what you're asking (and maybe about what you're 'really asking').
因此,我将给出一个答案,其中包括对您所询问的内容(以及您“真正询问”的内容)的一些假设。
You should consider that Brad M in his comments is asking what I view as an important question.你应该考虑到 Brad M 在他的评论中问的是我认为的一个重要问题。 Part of the reason I believe this is that the way you've structured your Entity Class, you seem to be 'instructing' (via Convention, not Configuration) EF to treat RelatedItemID as a Foreign Key, which would make me question whether it's true that you "don't need the Foreign Key"
我相信这是您构建实体类的方式的部分原因,您似乎在“指示”(通过约定,而不是配置)EF 将 RelatedItemID 视为外键,这让我怀疑这是否正确你“不需要外键”
So the 'quick and easy answer' is that you could restructure the class so that you won't be 'instructing EF via Convention to generate a Foreign Key' (like renaming the RelatedItemId attribute).因此,“快速而简单的答案”是您可以重组类,这样您就不会“通过约定指示 EF 生成外键”(例如重命名 RelatedItemId 属性)。 Or you might be able to use one of the 'Configuration' methods to override this (for instance, Fluent API );
或者您可以使用“配置”方法之一来覆盖它(例如, Fluent API ); I'm less sure of this.
我不太确定这一点。
Bear in mind that doing so means you'll lose any of the benefits of Foreign Keys in the instances where your RelatedItemId 'points to' a RelatedItem that does exist in the data store.请记住,这样做意味着在您的 RelatedItemId “指向”数据存储中确实存在的 RelatedItem 的情况下,您将失去外键的任何好处。 That might be fine for you;
这对你来说可能没问题; but if it isn't, you'd probably need to reconsider (in light of Brad M's comment) what you're trying to accomplish and how, perhaps post further questions, etc.
但如果不是,您可能需要重新考虑(根据 Brad M 的评论)您要完成的任务以及如何完成,或者发布更多问题等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.