问题
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