2

I am desperately trying to implement a nullable foreign key with the Entity Framework model designer.

The tables in question look like this:

EF Model

The settings should be correct, as my class is generated accordingly with the Sender property as follows:

public Nullable<int> SenderId { get; set; }

However, when calling Context.Database.Create(); the created databases SenderId property is not nullable.

If I manually change the columns type to a nullable in the database, I get an error within EF that the model and the database differ.

Any advice?

Thanks!

2
  • 1
    Try to "Generate Database from Model" in designer. It will generate a DDL script for database. Check if a field has correct type there. If it still show incorrect type. Try to remove association and the field and create association again. It should create a field automatically. Commented Jan 6, 2017 at 21:54
  • Ok, the script generates the database correctly (for whatever reason). If I try using the Order table within my code now, it still throws an EntityCommandCompilationException because the column apparently doesn't support null values while the entity model's column does. Commented Jan 6, 2017 at 22:33

2 Answers 2

2

I had the same problem like you

Try to set your senderid like this:

   public int? SenderId { get; set; }

If this doesnt help you, you can change the property as shown above and modify the database manually, after you've done that. there should be no difference.

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

1 Comment

The class is created properly, as shown in my question (the property is created as a Nullable). Problem was it didn't work even though the properties were correct... but thanks anyway!
0

Okay, after messing around for a few hours, I finally got to the source of the problem: the edmx-file of my Entity model.

While the Visual Studio Entity Model Designer showed me that the column is nullable (or rather I set it to nullable), I had to find out that the .edmx file itself didn't apply these changes. I manually changed the .edmx file within an editor.

<Property Name="SenderId" Type="Int32" Nullable="true" />

The Nullable property was originally set to false... By the way: the associations weren't saved either, I had to set the 0..1 association myself within the text editor, since the foreign key is now nullable. Thanks for the help anyway!

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.