Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 处理外键约束时出错_Sql Server 2008_C# 4.0_Ef Code First_Foreign Keys_Data Migration - Fatal编程技术网

Sql server 2008 处理外键约束时出错

Sql server 2008 处理外键约束时出错,sql-server-2008,c#-4.0,ef-code-first,foreign-keys,data-migration,Sql Server 2008,C# 4.0,Ef Code First,Foreign Keys,Data Migration,我目前正在处理的一个项目有一个外键问题。我首先使用实体代码来创建数据库。以下是我到目前为止的情况 桌子 单位:Id 类别:Id CategoryUnits:Id、CategoryId、UnitId 代码优先 C类 public partial class Category : BaseEntity, ILocalizedEntity { private ICollection<CategoryUnits> _categoryUnits; ... publi

我目前正在处理的一个项目有一个外键问题。我首先使用实体代码来创建数据库。以下是我到目前为止的情况

桌子 单位:Id

类别:Id

CategoryUnits:Id、CategoryId、UnitId

代码优先 C类

public partial class Category : BaseEntity, ILocalizedEntity
{
    private ICollection<CategoryUnits> _categoryUnits;

    ...

    public virtual ICollection<CategoryUnits> CategoryUnits
    {
        get { return _categoryUnits ?? (_categoryUnits = new List<CategoryUnits>()); }
        protected set { _categoryUnits = value; }
    }
}
CategoryUnits.cs

public partial class CategoryUnits : BaseEntity, ILocalizedEntity
{
    public virtual int UnitId { get; set; }
    public virtual int CategoryId { get; set; }

    public virtual Units Unit { get; set; }
    public virtual Category Category { get; set; }
}
CategoryUnitsMap.cs

public partial class CategoryUnitsMap : EntityTypeConfiguration<CategoryUnits>
{
    public CategoryUnitsMap()
    {
        this.ToTable("CategoryUnits");
        this.HasKey(cu => cu.Id);

        this.HasRequired(cu => cu.Unit)
            .WithMany()
            .HasForeignKey(cu => cu.UnitId);

        this.HasRequired(cu => cu.Category)
            .WithMany(c => c.CategoryUnits)
            .HasForeignKey(cu => cu.CategoryId);
    }
}
public分部类CategoryUnitsMap:EntityTypeConfiguration
{
公共类别YUnitsMap()
{
本表为ToTable(“分类”);
this.HasKey(cu=>cu.Id);
此.HasRequired(cu=>cu.Unit)
.有很多
.HasForeignKey(cu=>cu.UnitId);
this.HasRequired(cu=>cu.Category)
.WithMany(c=>c.CategoryUnits)
.HasForeignKey(cu=>cu.CategoryId);
}
}
当前发生的情况是,在数据迁移程序中尝试插入数据时,我收到以下消息:

INSERT语句与外键约束“CategoryUnits_Category”冲突。冲突发生在数据库“NopDB3”、表“dbo.Category”、列“Id”中

这是我实际将数据放入表中的代码

Program.cs

private static void AddDefaultOfficeSuppliesUnitRights()
    {
        try
        {
            var unitIds = new List<int>();
            var sqlSelectStatement = "Select * From Units With(NoLock)";
            var units = new DataSet();

            using (var sqlCommand = new SqlCommand(sqlSelectStatement, sqlCon))
            {
                var sqlAdapter = new SqlDataAdapter();
                sqlAdapter.SelectCommand = sqlCommand;
                sqlCon.Open();
                sqlAdapter.Fill(units);
                sqlCon.Close();
            }

            foreach (DataRow dr in units.Tables[0].Rows)
            {
                var unitId = Int32.Parse(dr["Id"].ToString());
                unitIds.Add(unitId);
            }

            var sqlInsertStatement = GenerateCategoryUnitsForOfficeSupplies("Insert Into CategoryUnits (UnitId, CategoryId) Values (cuUnitId, 19)", unitIds);
            using (var sqlCommand = new SqlCommand(sqlInsertStatement, sqlCon))
            {
                sqlCon.Open();
                sqlCommand.ExecuteNonQuery();
                sqlCon.Close();
            }

            Console.WriteLine("Default Office Supply CategoryUnits Added");
        }
        //Something went wrong
        catch (Exception ex)
        {
            Console.WriteLine("Error in Add Default Category Units for Office Supplies: " + ex.Message);
        }
        //Close out sql connection
        finally
        {
            if (sqlCon.State != ConnectionState.Closed) sqlCon.Close();
        }
    }

private static string GenerateCategoryUnitsForOfficeSupplies(string sqlInsertStatement, List<int> unitIds)
    {
        var sqlInsertStatements = string.Empty;
        foreach (var unitId in unitIds)
        {
            sqlInsertStatements += sqlInsertStatement.Replace("cuUnitId", unitId.ToString()) + "; ";
        }

        return sqlInsertStatements;
    }
private static void AddDefaultOfficeSuppliesUnitRights()
{
尝试
{
var unitIds=新列表();
var sqlSelectStatement=“从带有(NoLock)的单位中选择*”;
var units=新数据集();
使用(var sqlCommand=newsqlcommand(sqlSelectStatement,sqlCon))
{
var sqlAdapter=新的SqlDataAdapter();
sqlAdapter.SelectCommand=sqlCommand;
sqlCon.Open();
sqlAdapter.Fill(单位);
sqlCon.Close();
}
foreach(数据行单位为dr。表[0]。行)
{
var unitId=Int32.Parse(dr[“Id”].ToString());
unitId。添加(unitId);
}
var sqlInsertStatement=GenerateCategoryUnitsfoficeSupplies(“插入到CategoryUnits(UnitId,CategoryId)值(cuUnitId,19)”,UnitId);
使用(var sqlCommand=newsqlcommand(sqlInsertStatement,sqlCon))
{
sqlCon.Open();
sqlCommand.ExecuteNonQuery();
sqlCon.Close();
}
Console.WriteLine(“添加默认办公用品类别”);
}
//出了点问题
捕获(例外情况除外)
{
Console.WriteLine(“添加办公用品默认类别单位时出错:“+ex.Message”);
}
//关闭sql连接
最后
{
if(sqlCon.State!=ConnectionState.Closed)sqlCon.Close();
}
}
私有静态字符串GenerateCategoryUnitsFrofficesupplies(字符串sqlInsertStatement,列表UnitId)
{
var sqlInsertStatements=string.Empty;
foreach(单位ID中的单位ID变量)
{
sqlInsertStatements+=sqlInsertStatement.Replace(“cuUnitId”,unitId.ToString())+“;”;
}
返回sqlInsertStatements;
}

最奇怪的是,当我通过sql语句手动插入数据时,它工作正常,没有错误。任何建议都会有帮助。

很可能您正在将数据插入外键字段,而该字段的主键列中没有相应的值……您是对的。几分钟前,我意识到我需要的分类数据还没有填充。我已经将触发默认数据加载的方法移动到迁移的最后。谢谢如果这很酷的话,我会回答上面的问题?。。。
private static void AddDefaultOfficeSuppliesUnitRights()
    {
        try
        {
            var unitIds = new List<int>();
            var sqlSelectStatement = "Select * From Units With(NoLock)";
            var units = new DataSet();

            using (var sqlCommand = new SqlCommand(sqlSelectStatement, sqlCon))
            {
                var sqlAdapter = new SqlDataAdapter();
                sqlAdapter.SelectCommand = sqlCommand;
                sqlCon.Open();
                sqlAdapter.Fill(units);
                sqlCon.Close();
            }

            foreach (DataRow dr in units.Tables[0].Rows)
            {
                var unitId = Int32.Parse(dr["Id"].ToString());
                unitIds.Add(unitId);
            }

            var sqlInsertStatement = GenerateCategoryUnitsForOfficeSupplies("Insert Into CategoryUnits (UnitId, CategoryId) Values (cuUnitId, 19)", unitIds);
            using (var sqlCommand = new SqlCommand(sqlInsertStatement, sqlCon))
            {
                sqlCon.Open();
                sqlCommand.ExecuteNonQuery();
                sqlCon.Close();
            }

            Console.WriteLine("Default Office Supply CategoryUnits Added");
        }
        //Something went wrong
        catch (Exception ex)
        {
            Console.WriteLine("Error in Add Default Category Units for Office Supplies: " + ex.Message);
        }
        //Close out sql connection
        finally
        {
            if (sqlCon.State != ConnectionState.Closed) sqlCon.Close();
        }
    }

private static string GenerateCategoryUnitsForOfficeSupplies(string sqlInsertStatement, List<int> unitIds)
    {
        var sqlInsertStatements = string.Empty;
        foreach (var unitId in unitIds)
        {
            sqlInsertStatements += sqlInsertStatement.Replace("cuUnitId", unitId.ToString()) + "; ";
        }

        return sqlInsertStatements;
    }