No chyba znowu nie.
tylko trzeba wpisać .WillCascadeOnDelete(true);
EF6.1.3
Tworzy się ładna definicja w DB z Delete Rule - Cascade - czyli to samo co ustawiłbyś w bazie.
I jak wywalisz rodzica contect.Entity.Remove()
To usunie też dzieci nawet przy wyłączonym LazyLoading (można zobaczyć w debugerze, ze nie ładuje dzieci). Aż sprawdziłem i tak to działa.
W drugim using widać, ze Person nie ładuje adresów.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF_Cascade
{
class Program
{
static void Main(string[] args)
{
using (var db = new EFContext()) {
var a = new Address { Adres = "adres1" };
var a1 = new Address { Adres = "adres2" };
var p = new Person { Name = "Name 1" };
p.Adresses.Add(a);
p.Adresses.Add(a1);
db.Persons.Add(p);
db.SaveChanges();
}
using (var db = new EFContext())
{
var pd = db.Persons.FirstOrDefault(x => x.Name == "Name 1");
db.Persons.Remove(pd);
db.SaveChanges();
}
}
}
public class Person
{
public Person()
{
Adresses = new List<Address>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Adresses { get; set; }
}
public class Address
{
public int Id { get; set; }
public virtual Person Person { get; set; }
public string Adres { get; set; }
}
public class EFContext : DbContext
{
public EFContext() : base("name=ef_cascadedeelte")
{
//Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
//Database.SetInitializer<SprayerDataContext>(new DropCreateDatabaseIfModelChanges<SprayerDataContext>());
//Database.SetInitializer<SprayerDataContext>(new CreateDatabaseIfNotExists<SprayerDataContext>());
}
public DbSet<Person> Persons { get; set; }
public DbSet<Address> Addresses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Address>()
.HasOptional<Person>(x=>x.Person)
.WithMany(x=>x.Adresses)
.WillCascadeOnDelete(true);
}
}
}