Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow null foreign key GUID

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 ?

like image 374
kartal Avatar asked Sep 23 '14 16:09

kartal


2 Answers

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; }
like image 177
Ted Elliott Avatar answered Oct 22 '22 02:10

Ted Elliott


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?

like image 21
Chaholl Avatar answered Oct 22 '22 02:10

Chaholl