2

I have an Item class with a RelatedItemId property. RelatedItemId can reference another Item that does not yet exist in the database.

In this case, I want item.RelatedItem == null.

How to tell EF to not create a foreign key for this field?

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:

enter image description here

I'm looking way to have it like this:

enter image description here

2
  • Why would you not want EF to create the foreign key? The model you describe looks fine, except the RelatedItem should be virtual. Commented Jan 29, 2017 at 22:09
  • I what to avoid foreign key generation in database. Commented Jan 29, 2017 at 22:13

1 Answer 1

2

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. 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"

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). Or you might be able to use one of the 'Configuration' methods to override this (for instance, 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. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.