编辑:如果我删除
RelatedItems
属性,问题就不存在。
创建实体类型
PlayerFurnitureItemPlacementData
的记录后,它会尝试使用不存在的列进行插入。
生成签名:
INSERT INTO `player_furniture_item_placement_data` (`created_at`, `direction`, `player_furniture_item_id`, `player_furniture_item_wired_data_id`, `position_x`, `position_y`, `position_z`, `room_id`, `wall_position`)
player_furniture_item_wired_data_id
从来不存在,EF从哪里得到这个?
完整代码:
new PlayerFurnitureItemPlacementData
{
RoomId = room.Id,
PlayerFurnitureItemId = playerItem.Id,
PlayerFurnitureItem = playerItem,
PositionX = x,
PositionY = y,
PositionZ = z,
WallPosition = string.Empty,
Direction = (HDirection) direction,
CreatedAt = DateTime.Now
};
dbContext.Entry(roomFurnitureItem.PlayerFurnitureItem).State = EntityState.Unchanged;
dbContext.RoomFurnitureItems.Add(roomFurnitureItem);
实体(如果不相关则被截断):
public class PlayerFurnitureItemPlacementData
{
[Key] public int Id { get; init; }
public int PlayerFurnitureItemId { get; init; }
public required PlayerFurnitureItem PlayerFurnitureItem { get; init; }
public int RoomId { get; init; }
public Room? Room { get; init; }
}
public class PlayerFurnitureItem
{
public int Id { get; init; }
public int PlayerId { get; set; }
public Player? Player { get; set; }
public FurnitureItem? FurnitureItem { get; init; }
public PlayerFurnitureItemPlacementData? PlacementData { get; set; }
public PlayerFurnitureItemWiredData? WiredData { get; set; }
public DateTime CreatedAt { get; init; }
}
public class PlayerFurnitureItemWiredData
{
[Key] public int Id { get; init; }
public int PlayerFurnitureItemId { get; init; }
public required PlayerFurnitureItem PlayerFurnitureItem { get; init; }
public required ICollection<PlayerFurnitureItemPlacementData> RelatedItems { get; init; }
}
实体框架(EF)自动从导航属性及其相关实体构造外键和连接,因此通过显式定义,它应该可以解决问题。
PlayerFurnitureItemPlacementData class
public int? PlayerFurnitureItemWiredDataId { get; set; }
public PlayerFurnitureItemWiredData? PlayerFurnitureItemWiredData { get; set; }
在 OnModelBinding 方法上显式定义关系
modelBuilder.Entity<PlayerFurnitureItemPlacementData>()
.HasOne(p => p.PlayerFurnitureItemWiredData)
.WithMany(w => w.RelatedItems)
.HasForeignKey(p => p.PlayerFurnitureItemWiredDataId);