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 ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
kartal
  • 17,436
  • 34
  • 100
  • 145
  • Possible dup of http://stackoverflow.com/questions/12768987/null-able-foreign-key-entity-framework-5-0-model-first – Mrchief Sep 23 '14 at 16:51
  • 1
    I don't think so it is duplication because I don't have a problem with Int I have only with GUID – kartal Sep 23 '14 at 16:57
  • 1
    @Mrchief this is not a duplicate. It's a completely different issue. – BrainSlugs83 Jul 17 '15 at 00:56
  • 1
    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. :( – BrainSlugs83 Jul 17 '15 at 00:58
  • 1
    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 `null` – Gonzo345 Jan 23 '20 at 07:01
  • @Gonzo345 How did you tell your entity to use `null` instead of `Guid.Empty`? – Jwags Nov 03 '20 at 00:25

2 Answers2

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; }
Ted Elliott
  • 3,415
  • 1
  • 27
  • 30
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?

Community
  • 1
  • 1
Chaholl
  • 455
  • 5
  • 8