Allow null foreign key GUID

拜拜、爱过 提交于 2019-11-30 17:01:50

问题


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 ?


回答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; }



回答2:


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?



来源:https://stackoverflow.com/questions/26000345/allow-null-foreign-key-guid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!