【发布时间】:2021-07-02 00:13:31
【问题描述】:
我在我的项目中使用代码优先方法。我也在尝试创建动态Create 动作和动态Complete(UnitOfWork) 动作。在我的函数添加第一个值后,我得到了这个错误。
让我向您展示我的功能:
public void WebFairHallSeatingCreator(int webFairHallID)
{
int[] hallSeatingOrderColumnValue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
string[] hallSeatingOrderRowValue = { "a", "b", "c", "d", "e", "f", "g" };
var hallSeatingOrder = new HallSeatingOrder();
for (int row = 0; row < hallSeatingOrderRowValue.Length; row++)
{
for (int col = 1; col <= hallSeatingOrderColumnValue.Length; col++)
{
if ((hallSeatingOrderRowValue.GetValue(row).ToString() == "c") || (hallSeatingOrderRowValue.GetValue(row).ToString() == "d"))
{
if ((col == 5) || (col == 6) || (col == 7))
{
hallSeatingOrder.HallSeatingOrderRowValue = "x";
hallSeatingOrder.HallSeatingOrderColumnValue = 15;
_unitOfWorkWFH.RepositoryHallSeatingOrder.Create(hallSeatingOrder);
}
else
{
hallSeatingOrder.HallSeatingOrderRowValue= hallSeatingOrderRowValue.GetValue(row).ToString();
hallSeatingOrder.HallSeatingOrderColumnValue = col;
hallSeatingOrder.WebFairHallID = webFairHallID;
_unitOfWorkWFH.RepositoryHallSeatingOrder.Create(hallSeatingOrder);
_unitOfWorkWFH.Complete();// This is the point
}
}
else
{
hallSeatingOrder.HallSeatingOrderRowValue = hallSeatingOrderRowValue.GetValue(row).ToString();
hallSeatingOrder.HallSeatingOrderColumnValue = col;
hallSeatingOrder.WebFairHallID = webFairHallID;
_unitOfWorkWFH.RepositoryHallSeatingOrder.Create(hallSeatingOrder);
_unitOfWorkWFH.Complete();// This is the point
}
}
}
}
这是我的HallSeatingOrder 课程:
public class HallSeatingOrder : Base
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int HallSeatingOrderID { get; set; }
[Required]
public int WebFairHallID { get; set; }
public int? CompanyID { get; set; }
[Required]
public int HallSeatingOrderColumnValue { get; set; }
[Required]
public string HallSeatingOrderRowValue { get; set; }
public bool HallSeatingOrderIsSpecial { get; set; }
public Company Company { get; set; }
public WebFairHall WebFairHall { get; set; }
}
public class HallSeatingOrderConfiguration : IEntityTypeConfiguration<HallSeatingOrder>
{
public void Configure(EntityTypeBuilder<HallSeatingOrder> builder)
{
builder.HasKey(x => x.HallSeatingOrderID);
builder.HasOne(x => x.Company)
.WithMany(x => x.HallSeatingOrders)
.HasForeignKey(x => x.CompanyID)
.OnDelete(DeleteBehavior.NoAction);
builder.HasOne(x => x.WebFairHall)
.WithMany(x => x.HallSeatingOrders)
.HasForeignKey(x => x.WebFairHallID)
.OnDelete(DeleteBehavior.NoAction);
}
}
我已经从我的问题中排除了每一个问题。
我尝试使用ValueGeneratedOnAdd() 和[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)],但没有一个对我有用。
【问题讨论】:
-
不要在循环中重复使用单个实体实例来创建多个实体。这个
var hallSeatingOrder = new HallSeatingOrder();应该在每个调用Create的块内。 -
我会试着让你知道@IvanStoev
-
它真的对我有用。非常感谢
标签: sql asp.net asp.net-core entity-framework-core ef-code-first