I’m trying to get Entity Framework to create the tables in a certain way for a special 1-to-1 relation.
Let’s say I have this set of classes:
public class Parent
{
public int ID { get; set; }
public string Title { get; set; }
public Child XYZ { get; set; }
}
public class Child
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
}
The XYZ property of the Parent class MAY be set to an instance of Child. I would like EF to create a table for each of the two classes, and the table for Child objects should simply have a foreign key column, ideally named “ParentID”, to keep the relation with the Parent object.
I do not want a “ChildID” column in the Parent table, and I do not want to add an ID or ParentID property to the Child class.
Currently, the properties of the Child object are created as columns in the Parent table, AND I get an exception if the XYZ property is not set to an instance of a Child class, i.e. it can’t be null.
I’m trying to do this with the DbModelBuilder and the OnModelCreating event. The IsOptional method only work with simple types.
Any suggestions? Is this even possible with EF?
Yes it cannot be null because currently your
Childis a complex type (value object) and it must be always set (it is part of the entity and entity doesn’t exist without this part). If the content of the complex type is optional you must enforce this on Child’s properties not onChilditself.If you want to have
Childmapped to separate table it must haveIDbecause every entity must have primary key. That ID will be also used as foreign key toParentto achieve one-to-one relation:And relation mapping: