下面是我的課:刪除基於狀態的多個ID記錄
public partial class Ads
{
public int Id { get; set; }
public int RegionId { get; set; }
public string Name { get; set; }
public int Group { get; set; }
}
記錄:
Id Name Group
1 abc 1
2 xyz 1
3 lmn 1
4 xxx 2
5 ppp 2
6 ttt 3
7 ggg 3
現在我想刪除所有記錄/只,與同組的特定的ID記錄一些ID。
代碼:
public void Delete(int[] ids,bool flag = false)
{
using (var context = new MyEntities())
{
context.Ads.RemoveRange(
context.Ads.Where(t => (flag ?
(context.Ads.Any(x => ids.Contains(x.Id) && x.Group == t.Group)) : false)));
context.SaveChanges();
}
}
我所試圖做的是類似下面的東西:
If flag is false with ids=3,5 then
I want to delete only records with Id=3,5
Else if flag is true with ids=3,5 then
I want to delete records with Id=3,5 but all other records too of the group to which ids=3,5 belong to.
Here id=3 belongs to group 1 so I want to delete all records of group1 i.e id=1,2 like wise ids=5 belongs to
group 2 so I want to delete all records of group 2 i.e id=4.
預計產量爲這最後的情況下(標誌=真):
Id Name Group
6 ttt 3
7 ggg 3
但是我認爲我沒有這樣做是一種正確的方式,並且查詢中有一些改進的來源。
注意: ids []將始終包含來自不同組的id和來自不同組的最高ID。
我該如何改善我的查詢兩種情況(標誌= true和false)?
嗨學習。請回顧一下[我之前提供的]建議(https://stackoverflow.com/questions/46450952/how-to-delete-child-automatically-based-on-parent-deletion-for-database-first-ap#comment79865111_46450952) ,即:當提及自己時,請始終使用大寫字母「I」。英語母語讀者通常覺得它很容易閱讀「我」,而輕微的挫折反應可能會影響到你的幫助._你會記得在你的下一篇文章中解決這個問題嗎? – halfer