Search code examples
c#entity-frameworkrelationshipcode-first

Entity Framework - Add existing foreign key to class structure


I have class like this:

public class Bundle
{
    public int Id { get; set; }

    public DateTime CreateDate { get; set; }

    public Child Something { get; set; }
}

EF created a table like this:

| Id | CreateDate | Something_Id | 

What i'm trying now, is to add the Something_Id foreign key to the class. I don't want to load the whole 'Something'-object just to get it's Id. However EF demands a DB-update and the db update with the manually added integer property 'Something_Id' fails because Something_Id is not nullable. How can i add this foreign key to the class structure without loosing data or relations?


Solution

  • Ok stupid mistake on my side. The null-exception actually gave the hint. One entry in the database did not have a foreign-key set, therefore the class structure was not allowed to be non-nullable and the update failed.