Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created November 12, 2018 13:26
Show Gist options
  • Save danielplawgo/a97aea0dd6b54f4343b4c360764f2eb9 to your computer and use it in GitHub Desktop.
Save danielplawgo/a97aea0dd6b54f4343b4c360764f2eb9 to your computer and use it in GitHub Desktop.
EF Plus - aktualizacja wielu obiektów jednym zapytaniem
public class BaseModel
{
public BaseModel()
{
IsActive = true;
}
public int Id { get; set; }
public bool IsActive { get; set; }
}
public class Category : BaseModel
{
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
private static void DeleteWithEFPlus()
{
using (var db = new DataContext())
{
using (var transaction = db.Database.BeginTransaction())
{
var category = db.Categories.FirstOrDefault(c => c.IsActive);
if (category == null)
{
return;
}
category.IsActive = false;
db.Products.Where(p => p.CategoryId == category.Id)
.Delete();
db.SaveChanges();
transaction.Commit();
}
}
}
public class Product : BaseModel
{
public string Name { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
private static void SoftDelete()
{
using (var db = new DataContext())
{
var category = db.Categories.FirstOrDefault(c => c.IsActive);
if (category == null)
{
return;
}
category.IsActive = false;
foreach (var product in category.Products)
{
product.IsActive = false;
}
db.SaveChanges();
}
}
private static void SoftDeleteWithEFPlus()
{
using (var db = new DataContext())
{
var category = db.Categories.FirstOrDefault(c => c.IsActive);
if (category == null)
{
return;
}
category.IsActive = false;
db.Products.Where(p => p.CategoryId == category.Id)
.Update(p => new Product() { IsActive = false });
db.SaveChanges();
}
}
private static void SoftDeleteWithEFPlusWithTransaction()
{
using (var db = new DataContext())
{
using (var transaction = db.Database.BeginTransaction())
{
var category = db.Categories.FirstOrDefault(c => c.IsActive);
if (category == null)
{
return;
}
category.IsActive = false;
db.Products.Where(p => p.CategoryId == category.Id)
.Update(p => new Product() { IsActive = false });
db.SaveChanges();
transaction.Commit();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment