2014-09-23 91 views
4

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

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

public virtual User CreatedBy { get; set; } 

但是当我添加迁移和更新数据库不让它能够在SQL表设计空。

有没有另一种方法让它首先通过模型允许null?

+0

可能DUP http://stackoverflow.com/questions/12768987/null-able-foreign-key -entity-framework-5-0-model-first – Mrchief 2014-09-23 16:51:37

+1

我不这么认为是重复的,因为我没有Int问题我只有GUID – kartal 2014-09-23 16:57:33

+1

@Mrchief这不是重复的。这是一个完全不同的问题。 – BrainSlugs83 2015-07-17 00:56:58

回答

0

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

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

当添加一个迁移您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?