我目前正在处理的项目中遇到外键问题。我首先使用实体代码来创建我的数据库。这是我到目前为止所拥有的。
表
单位:身份证,...
类别:身份证,...
CategoryUnits:Id、CategoryId、UnitId
代码优先
类别.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; }
}
}
单位.cs
public class Units : BaseEntity
{
...
}
类别单位.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”列中。
这是我实际将数据放入表中的代码。
程序.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 语句手动插入数据时,它工作正常并且没有错误。任何的意见都将会有帮助。