C# EF:“;ReferentialConstraint中的从属属性映射到存储生成的列”;换身份证

C# EF:“;ReferentialConstraint中的从属属性映射到存储生成的列”;换身份证,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,正如标题所说,我遇到了这个错误。我在谷歌上搜索,找不到答案,因为如果我使用sql进行插入,就可以了,而当我使用ef进行添加时,它就无法工作。请看下面,这是我的数据库模式。 当我尝试向good表添加一些内容时,出现了错误。good的fluent api如下所示: using ppdai.user.vip.model; using System; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity

正如标题所说,我遇到了这个错误。我在谷歌上搜索,找不到答案,因为如果我使用sql进行插入,就可以了,而当我使用ef进行添加时,它就无法工作。请看下面,这是我的数据库模式。

当我尝试向good表添加一些内容时,出现了错误。good的fluent api如下所示:

using ppdai.user.vip.model;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;

namespace ppdai.user.vip.model.mapping
{
public class GoodsMapping: EntityTypeConfiguration<Goods>
{
    public GoodsMapping()
    {
        this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        this.HasKey(x => x.Id);


        this.Property(x => x.GoodsQuantity).IsRequired();
        this.Property(x => x.GoodPrice).IsRequired();
        this.Property(x => x.GoodScore).IsRequired();
        this.Property(x => x.GoodTypeId).IsRequired();

        this.HasRequired(x => x.GoodType)
            .WithMany(x => x.Goods)
            .HasForeignKey(x => x.GoodTypeId);


    }

}
 }
使用ppdai.user.vip.model;
使用制度;
使用System.ComponentModel.DataAnnotations.Schema;
使用System.Data.Entity.ModelConfiguration;
使用System.Data.Entity.ModelConfiguration.Configuration;
命名空间ppdai.user.vip.model.mapping
{
公共类GoodsMapping:EntityTypeConfiguration
{
公共物品映射()
{
this.Property(x=>x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.HasKey(x=>x.Id);
this.Property(x=>x.GoodsQuantity).IsRequired();
this.Property(x=>x.GoodPrice).IsRequired();
this.Property(x=>x.GoodScore).IsRequired();
this.Property(x=>x.GoodTypeId).IsRequired();
this.HasRequired(x=>x.GoodType)
.有许多(x=>x.货物)
.HasForeignKey(x=>x.GoodTypeId);
}
}
}

因此,“中心”表在我的数据库中的位置很好,有人知道如何解决吗?

看起来您的一个外键列被设置为由数据库生成。 检查
Goods
中的
GoodTypeId
是否未设置为自动递增标识。
同时检查
OrderItems
中的
GoodId
HomePageProducts
中的
GoodId
是否相同,所有foregin键都不是标识,我认为它与foregin键无关,因为我取消了goods表的foregin键,它仍然触发相同的异常。如果我使用not identity属性设置Id,它将显示“无法插入,因为设置的identity\u insert处于关闭状态”。您报告的错误与主键无关,与外键有关。此外,您不必显式地设置数据库生成的主键。按照惯例,密钥将自动设置为DatabaseGenerated。也检查其他外键,不仅仅是商品表中的外键。没有外键是由生成的数据库设置的,我仔细检查,当我使用sql插入时,它可以工作,为什么?但ef不能解决它,正如您所说,这是由于彩票表的主键是goodId,商品表的主键是id,而且彩票和good是一对一的关系,所以如果我创建good表,默认情况下标识是关闭的。会出现很多问题。您通过
.HasForeignKey(x=>x.GoodTypeId)定义了foregin键
@AliSoltani与您无关,因为我删除了外键,但它仍然无法工作。