Entity Framework: one or more of the foreign-key properties is non-nullable

c# entity-framework entity-framework-6 exception sql-server

Popular Answer

To resolve this issue, you must examine your object.

Here is some basic code to describe yourException :

static void Main()
    using (MyDbContext ctx = new MyDbContext())
        // Build a new object
        MyClass o = new MyClass() { Id = 1, ChildObject = null };

        // Add it to your Context (It's not in the DB yet!)

        // Write all changes (the new object) to the Db

// You got some DbContext with a DbSet pointing to your Table "MyTable"
public class MyDbContext : DbContext
    public DbSet<MyClass> MyObjects { get; set; }

// You've got a class to map your table to some nice object.
public class MyClass
    // Some column..
    public int Id { get; set; }

    // And some ForeignKey! Which maps a column with the Id to an object.
    public MyClass ChildObject { get; set; }

I establish a context, add an item, and save the changes in this example (create an Insert to the table).

First of all, the exception is thrown during SaveChanges because the property "ChildObject" is unrestricted and may be changed to null.

Second: The error is a database error. Your programme is (likely) operating properly. However, your Db informs you that a row in MyTable cannot exist without a reference to a ChildObject.

You need to consider if your software forgot to set the child variable or whether the database was setup incorrectly (make the column nullable).

Hope you can see: You must go deep inside your code. Your "whole model" has a fault, which you must fix.

Think about viewing the context's SQL-Log. Example:ctx.Log = Console.WriteLine; (I don't have a studio here, but I believe I ought to be something along these lines.)

You may perform the most recent SQL query on your database in this manner for improved error outputs.

8/28/2018 7:27:07 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow