处理外键约束时出错

时间:2012-10-29 14:46:59

标签: sql-server-2008 c#-4.0 ef-code-first foreign-keys data-migration

我正在处理正在处理的项目的外键问题。我正在使用Entity Code First创建我的数据库。这是我到目前为止所做的。

单位:Id,......

类别:Id,......

CategoryUnits:Id,CategoryId,UnitId

Code First

Category.cs

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; }
    }
}

Units.cs

public class Units : BaseEntity
{
    ...
}

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);
    }
}

目前正在发生的事情是当我尝试在数据迁移程序中插入数据时收到以下消息:

INSERT语句与FOREIGN KEY约束“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;
    }

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

0 个答案:

没有答案