Fix CRUD notes

This commit is contained in:
Marcello Lamonaca 2021-05-08 12:43:30 +02:00
parent cd1fa67960
commit 8b5e725208

View file

@ -88,31 +88,10 @@ dotnet ef database update
### Create
```cs
public static bool InsertOne(Entity entity)
{
int rows = 0;
context.Add(entity);
context.AddRange(entities);
using(var context = new Context())
{
context.Add(entity);
context.SaveChanges();
}
return rows == 1;
}
public static bool InsertMany(IEnumerable<Entity> entities)
{
int rows = 0;
using(var context = new Context())
{
context.AddRange(entities);
context.SaveChanges();
}
return rows == entities.Count();
}
context.SaveChanges();
```
### Read
@ -120,83 +99,27 @@ public static bool InsertMany(IEnumerable<Entity> entities)
[Referenced Object Not Loading Fix](https://stackoverflow.com/a/5385288)
```cs
public static List<Entity> SelectAll()
{
using(var context = new Context())
{
return context.Entities.ToList();
}
}
context.Entities.ToList();
context.Entities.Find(id);
static Entity SelectOneById(int id)
{
using(var context = new Context())
{
return context.Entities.Find(id);
// force read of foreign key identifying referenced obj
return context.Entities.Include(c => c.ForeignObject).Find(id);
}
}
// force read of foreign key identifying referenced obj
context.Entities.Include(c => c.ForeignObject).Find(id);
```
### Update
```cs
public static bool UpdateOne(Entity entity)
{
int rows = 0;
context.Entities.Update(entity);
context.UpdateRange(entities);
using(var context = new Context())
{
context.Entities.Update(entity);
context.SaveChanges();
}
return rows == 1;
}
public static bool UpdateMany(IEnumerable<Entity> entities)
{
int rows = 0;
using(var context = new Context())
{
context.UpdateRange(entities);
context.SaveChanges();
}
return rows == entities.Count();
}
context.SaveChanges();
```
### Delete
```cs
public static bool DeleteOne(Entity entity)
{
int rows = 0;
context.Entities.Remove(entity);
context.RemoveRange(entities);
using(var context = new Context())
{
context.Entities.Remove(entity);
context.SaveChanges();
}
return rows == 1;
}
public static bool DeleteMany(IEnumerable<Entity> entities)
{
int rows = 0;
using(var context = new Context())
{
context.RemoveRange(entities);
context.SaveChanges();
}
return rows == entities.Count();
}
context.SaveChanges();
```