Allow null foreign key GUID
Asked Answered
I

2

8

I want to create a nullable foreign key with type GUID like this

[ForeignKey("CreatedBy")]
[Display(Name = "Created by")]
public Guid? CreatedById { get; set; }

public virtual User CreatedBy { get; set; }

But when I add migration and update the database it doesn't make it allow null in table design in SQL.

Is there another way to make it allow null through model first ?

Incinerate answered 23/9, 2014 at 16:40 Comment(6)
Possible dup of #12769487Kroo
I don't think so it is duplication because I don't have a problem with Int I have only with GUIDIncinerate
@Kroo this is not a duplicate. It's a completely different issue.Apologetics
It's weird that making it nullable works for int but not with Guid. I wonder if it's a bug in EF? Still not fixed in EF 6. :(Apologetics
I stated the nullable Guid on my model too and I wasn't noticing any nullable: true on my brand new migration. Once applied, checked the relationships on the SMSS and saw it was allowing nulls. My problem was that I was trying to add Guid.Empty instead of a nullGammon
@Gammon How did you tell your entity to use null instead of Guid.Empty?Wadi
A
1

Not sure why yours doesn't work or if you figured it out. We have pretty much the same design and we get nullable foreign keys. We typically use Fluent config but we don't have any config on these properties as EF figures them out without help. Maybe removing the ForeignKey attribute might fix it.

public virtual User CreateUser { get; set; }
public Guid? CreateUserId { get; set; }
Abscise answered 25/4, 2016 at 13:17 Comment(0)
A
1

When adding a migration your OnModelCreating method is called to determine the current model configuration. In there, if you have code like this:

  modelBuilder.Entity<ParentEntity>()
        .HasMany(e => e.ChildEntity)
        .WithRequired(e => e.CreatedBy)
        .HasForeignKey(e => e.CreatedById);

then you're telling EF that CreatedById is required and therefore not nullable (from a SQL perspective).

To allow it to be nullable change the code to:

  modelBuilder.Entity<ParentEntity>()
        .HasMany(e => e.ChildEntity)
        .WithOptional(e => e.CreatedBy)
        .HasForeignKey(e => e.CreatedById);

See: How do OnModelCreating and non automatic Migrations relate?

Astereognosis answered 23/11, 2016 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.