sqlsugar 将实体insert
时间: 2023-08-22 10:35:08 浏览: 261
可以使用SqlSugar的Insertable方法来将实体插入到数据库中。
具体步骤如下:
1. 创建一个实体类,例如:
```csharp
public class User
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
```
2. 创建SqlSugar的实例:
```csharp
var db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "your_connection_string",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true
});
```
3. 创建Insertable对象并将实体传入:
```csharp
var user = new User() { Name = "Tom", Age = 18 };
var insertable = db.Insertable(user);
```
4. 调用ExecuteCommand方法将实体插入到数据库中:
```csharp
var result = insertable.ExecuteCommand();
```
其中,ExecuteCommand方法返回一个int类型的值,表示受影响的行数,如果插入成功,则值为1,否则为0。
需要注意的是,实体类中必须包含一个主键字段,并且主键字段的特性必须设置为[SugarColumn(IsPrimaryKey = true, IsIdentity = true)],以便SqlSugar能够正确地生成INSERT语句。
阅读全文
相关推荐

















