shawnseanshaun
shawnseanshaun

Reputation: 1107

Leave GUID null when adding entity to context

I have a Child model which has a property called EmergencyContactId. This property is a nullable GUID which points to my Contacts table when set (and yes, the column is set to nullable in the database). The problem is that when I call _context.Children.Add(newChild), newChild's EmergencyContactId property is automatically generated as a new GUID by EF, even though it's supposed to be null.

var id = newChild.EmergencyContactId;    // id is null.
_context.Children.Add(newChild);
id = newChild.EmergencyContactId;        // id is a new GUID.

So I tried going into my OnModelCreating of my database context and doing this:

child.Property(props => props.EmergencyContactId)
    .HasDefaultValue(null)
    .ValueGeneratedNever();

I thought that should fix the issue, but no such luck; the value is still auto-generated. I want EF to just leave the property alone; if it's null, it's supposed to be that way!

It doesn't seem like this should be so hard, but here we are. I'm at a complete loss for what to do next.

EDIT: My model

public class Child 
{
    // other properties


    #region EmergencyContact

    private Contact _emergencyContact = default(Contact);
    public virtual Contact EmergencyContact { get => _emergencyContact; set => _emergencyContact = value; }

    #endregion EmergencyContact


    #region EmergencyContactId

    private Guid? _emergencyContactId;
    public Guid? EmergencyContactId { get => _emergencyContactId; set => _emergencyContactId = value; }

    #endregion EmergencyContactId

    // other properties
}

and its configuration:

child.HasOne(props => props.EmergencyContact)
    .WithMany()
    .HasForeignKey(props => props.EmergencyContactId)
    .HasPrincipalKey(contact => contact.Id);

Upvotes: 1

Views: 786

Answers (1)

Max
Max

Reputation: 866

Is this EmergencyContactId not a relationship id? If it is, maybe you have set the object (probably called) EmergencyContact to an object. When that is the case, the EmergencyContactId will be filled automatically too with the Id of the EmergencyContact.

Upvotes: 3

Related Questions