Linq to Entities - 如何使用内部联接删除许多记录

时间:2015-10-28 18:12:53

标签: c# linq linq-to-entities

我有两个班级:

public class Address
{
    [Key]
    public int ID_Address { get; set; }

    public string URL { get; set; }

public class Category_Address
{
    [Key]
    public int ID_Category_Address { get; set; }



    public int ID_Category { get; set; }
    public virtual Category Category { get; set; }

    public int ID_Address { get; set; }
    public virtual Address Address { get; set; }

}

我想从ID_Address表格Address中选择URL = "anytextIwrite",并删除Category_Address中与我选择的ID_Address相同的所有记录。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

现在我用一些假设写了这个。显然,你想要使用你自己的数据库名称和你想要的任何组名,但这是一个相当简单的LINQ语句和连接,然后是一个应该做你想做的foreach。

var toDelete = from addr in addresses
   join cate in category_addresses on addr.id_address equals cate.id_address
   where addr.url = "anytextIwrite"
   select cate;

foreach (var record in toDelete) {
    db.category_addresses.DeleteOnSumbit(record);
}

答案 1 :(得分:0)

如果仍然有效,请尝试像这样:

using (var context = new YourDbModel())
{
    var deletingAddresses = context.Category_Addresses
                                   .Where(ca => ca.Address.URL == "anytextIwrite")
                                   .Select(ca => ca.Address)
                                   .ToArray();
    foreach(var address in deletingAddresses)
    {
        context.Category_Addresses.Attach(address);
        var entry = context.Entry(address);
        entry.State = EntityState.Deleted;
    }
    context.SaveChanges();
}

它对我有用,所以也许你也需要它。