【问题标题】:Code first The INSERT statement conflicted with the FOREIGN KEY constraint代码优先 INSERT 语句与 FOREIGN KEY 约束冲突
【发布时间】:2014-01-01 11:09:49
【问题描述】:

我刚刚开始使用代码优先方法来创建数据库。我有以下 3 个表:

public class TagDatabase
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TagID { get; set; }
    public string TagName { get; set; }
    public string Description { get; set; }
    public int Count { get; set; }

    [ForeignKey("TagTypes")]
    public virtual int TagTypeID { get; set; }
    public virtual ICollection<TagTypesDb> TagTypes { get; set; }

    [ForeignKey("Users")]
    public virtual int CreatedBy { get; set; }
    public virtual UsersDb Users { get; set; }
}

public class TagTypesDb
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TagTypeID { get; set; }
    public string TagTypeName { get; set; }
}

public class UsersDb
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserID { get; set; }
    public string UserName { get; set; }
}

这里 TagDatabse 和 User 和 TagType 有 1 对 1 的关系。我用于此的 fluent API 代码是:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TagDatabase>()
           .HasOptional(a => a.TagTypes)
           .WithMany()
           .HasForeignKey(u => u.TagTypeID);

        modelBuilder.Entity<TagDatabase>()
                    .HasRequired(a => a.Users)
                    .WithMany()
                    .HasForeignKey(u => u.CreatedBy);
}

现在我的问题是每当我尝试在 TagDatabase 中插入数据时,我都会遇到此异常:

TagDatabase_TagTypes: : Multiplicity conflicts with the referential constraint in Role 'TagDatabase_TagTypes_Target' in relationship 'TagDatabase_TagTypes'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

TagTypeId 属性允许为空。所以我在 OnModelCreating 方法中使用了 HasOptional()。

谁能告诉我如何解决这个问题以及我在这里缺少什么?

【问题讨论】:

  • 如果你说HasOptional(a =&gt; a.TagTypes),你应该让外键TagTypeID可以为空。
  • TagTypeId 在 TagDatabase 中是可为空的类型。所以我使用了 HasOptional(a => a.TagTypes) 。这是否正确
  • 您的财产不是。 TagDatabaseTagTypeID 属性应该是 int? 而不是 int

标签: c# linq entity-framework


【解决方案1】:

如果对应关系是可选的,则应设置外键属性nullable

public class TagDatabase
{
  //sniff...

 [ForeignKey("TagTypes")]
 public virtual int? TagTypeID { get; set; }      //Since TagTypes is optional, this should be nullable
 public virtual ICollection<TagTypesDb> TagTypes { get; set; }

 //sniff...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2020-07-27
    • 2021-05-30
    相关资源
    最近更新 更多