插入数据后,DataChangesExecuted事件中​entityInfo.EntityValue的主键是否可以赋值 返回

SqlSugar 沟通中
6 299
db.Aop.DataChangesExecuted = (oldValue, entityInfo) =>
{
    if (entityInfo.OperationType == DataFilterType.InsertByObject && entityInfo.EntityColumnInfo.IsPrimarykey)
    {
        Type type = entityInfo.EntityValue.GetType();
        var propertyInfo = type.GetProperty("Id");

        if (propertyInfo != null)
        {
            var value = propertyInfo.GetValue(entityInfo.EntityValue);
             // 插入数据后,这获得的id是空的,可以给它赋值吗?
            if (value is int id)
            {
               
            }
        }
    }
}


热忱回答6

  • fate sta fate sta VIP0
    2024/7/30

    理论上是可以赋值,问题是这个值你从哪儿来。

    0 回复
  • fate sta fate sta VIP0
    2024/7/30

    ExecuteCommandIdentityIntoEntity 你用这个方法试试

    0 回复
  • 试了ExecuteCommandIdentityIntoEntity实体的主键还是0


    这是测试代码:

    public class MyClass
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity =true)]
        public int Id { get; set; }
    
        public string? A { get; set; }
    }
    
    SqlSugarClient client = new (
       sqlSugarConnectionConfig, db =>
       {
           db.Aop.DataChangesExecuted = (oldValue, entityInfo) =>
           {
               if (entityInfo.OperationType == DataFilterType.InsertByObject && entityInfo.EntityColumnInfo.IsPrimarykey)
               {
                   Type type = entityInfo.EntityValue.GetType();
                   var propertyInfo = type.GetProperty("Id");
    
                   if (propertyInfo != null)
                   {
                       var value = propertyInfo.GetValue(entityInfo.EntityValue);
                        // value是null, id是0
                       if (value is int id)
                       {
    
                       }
                   }
               }
           };
       });
    
    _db.Insertable(new MyClass { A = "123" }).ExecuteCommandIdentityIntoEntity();


    0 回复
  • @fate sta 帮忙看一下

    0 回复
  • @fate sta:帮忙看一下,我在上面更新的测试代码

    0 回复
  • @fate sta:帮忙看一下,用ExecuteCommandIdentityIntoEntity 没有效果

    0 回复