【问题标题】:Allow null foreign key GUID允许空外键 GUID
【发布时间】:2014-09-23 16:40:19
【问题描述】:

我想像这样创建一个类型为GUID 的可为空的外键

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

public virtual User CreatedBy { get; set; }

但是当我添加迁移和更新数据库时,它不允许在 SQL 的表设计中为空。

是否有另一种方法可以使其首先通过模型允许 null ?

【问题讨论】:

  • 我不认为这是重复,因为我对 Int 没有问题,我只有 GUID
  • @Mrchief 这不是重复的。这是一个完全不同的问题。
  • 将其设为可空对 int 有效但对 Guid 无效,这很奇怪。我想知道这是否是EF中的错误?在 EF 6 中仍未修复。:(
  • 我也在我的模型上声明了nullable Guid,但在我的全新迁移中我没有注意到任何nullable: true。应用后,检查 SMSS 上的关系,发现它允许空值。我的问题是我试图添加 Guid.Empty 而不是 null

标签: c# asp.net-mvc entity-framework guid ef-model-first


【解决方案1】:

不知道为什么你的不起作用或者你是否明白了。我们有几乎相同的设计,我们得到可以为空的外键。我们通常使用 Fluent 配置,但我们没有对这些属性进行任何配置,因为 EF 在没有帮助的情况下计算它们。也许删除 ForeignKey 属性可能会解决它。

public virtual User CreateUser { get; set; }
public Guid? CreateUserId { get; set; }

【讨论】:

    【解决方案2】:

    添加迁移时,会调用您的 OnModelCreating 方法来确定当前的模型配置。在那里,如果你有这样的代码:

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

    然后你告诉 EF CreatedById 是必需的,因此不能为空(从 SQL 的角度来看)。

    为了让它可以为空,请将代码更改为:

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

    见:How do OnModelCreating and non automatic Migrations relate?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-29
      相关资源
      最近更新 更多