// 方式一,推荐
var newEntity = _testRepository.InsertWithSaveChanges(new TestEntity()
{
Name = "Monk",
CreatedTime = DateTime.Now
});
var newId = _testRepository.Id; // 最新Id
// 方式二
var newEntity = _testRepository.Entity.Add(new TestEntity()
{
Name = "Monk",
CreatedTime = DateTime.Now
});
_testRepository.SaveChanges();
var newId = _testRepository.Id;
新增多条数据,无需返回
var addEntities = new List<TestEntity>(){
new TestEntity()
{
Name = "Monk",
CreatedTime = DateTime.Now
},
new TestEntity()
{
Name = "MonkSoul",
CreatedTime = DateTime.Now
},
};
_testRepository.Insert(addEntities);
新增多条,并立即返回新增实体集合
var addEntities = new List<TestEntity>(){
new TestEntity()
{
Name = "Monk",
CreatedTime = DateTime.Now
},
new TestEntity()
{
Name = "MonkSoul",
CreatedTime = DateTime.Now
},
};
_testRepository.InsertWithSaveChanges(addEntities);
var entity = _testRepository.Find(1);
entity.Name = "MonkSoul";
entity.Age = 27;
_testRepository.SetModifyProperties(specEntity,
u => u.Name,
u => u.Age);
这种方式,无需调用 _testRepository.Update(entity) 和 _testRepository.SaveChanges()方法。但是会生成更新指定列的 Sql,比如这里是 Name 和 Age 两个属性
更新所有列,无需查询
var entity = new Entity { Name ="Monk", Age = 27, Id = 1};
_testRepository.EntityEntryState(entity) = EntityState.Modified;
注意:必须包含主键 Id
更新指定列,无需查询
var entity = new Entity { Name ="Monk", Age = 27, Id = 1};
_testRepository.Context.Attach(entity);
_testRepository.SetModifyProperties(entity,
u => u.Name,
u => u.Age);