我有这些课
public class HomeSection2
{
public HomeSection2()
{
HomeSection2Detail = new List<HomeSection2Detail>();
}
public Guid ID { get; set; }
public string Title { get; set; }
public string Header { get; set; }
public virtual List<HomeSection2Detail> HomeSection2Detail { get; set; }
}
public class HomeSection2Detail
{
public Guid ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public int? Sequence { get; set; }
public virtual HomeSection2 HomeSection2 { get; set; }
}
当我打电话
var obj2detail = obj2.HomeSection2Detail.Where(w => w.ID == detail.ID).FirstOrDefault();
if (obj2detail != null)
{
obj2.HomeSection2Detail.Remove(obj2detail);
}
从我的应用程序中,它只会删除关系,但不会删除数据库中的记录。
答案 0 :(得分:2)
您需要从HomeSection2Details
DbSet中明确删除该实体。
dbContext.HomeSection2Details.Remove(obj2detail);
答案 1 :(得分:1)
无需从 DbContext
中明确删除依赖实体;如果依赖实体在从其主体实体中删除时总是被删除,这可以通过在 DbContext
上使用 OnDelete
:
protected override void OnModelCreating(ModelBuilder builder)
{
builder
.Entity<HomeSection2>()
.HasMany(x => x.HomeSection2Detail)
.WithOne(x => x.HomeSection2)
.OnDelete(DeleteBehavior.Cascade); // Causes dependent entity to be deleted
}
答案 2 :(得分:0)
您需要执行以下操作。解释在片段中添加为注释:
var obj2detail = obj2.HomeSection2Detail.Where(w => w.ID == detail.ID).FirstOrDefault();
if (obj2detail != null)
{
// this line of code only delete the relationship.
obj2.HomeSection2Detail.Remove(obj2detail);
// If you want to delete the entity you need the DbContext help
// and your HomeSection2Details DbSet<HomeSection2Detail> like below
yourDbContext.HomeSection2Details.Remove(student);
}
答案 3 :(得分:0)
您直接使用 RemoveRange 或 Remove DbContext
_db.RemoveRange(obj2detail);