asp.NET LINQ从数据库中删除

时间:2015-11-13 17:28:56

标签: c# asp.net sql-server linq

我有一个带有2个表的SQL Server数据库:

t1 - 类别

Id
Name

t2-产品

Id
Name
CategoryId

我想从Category表中删除一行,但由于我有外键,我需要处理具有我要删除的CategoryId的产品。

所以我这样做了:

var ProdCatID = (from prod in DataContext.Products
                 where prod.CategoryId == Convert.ToInt32(Id)
                 select prod).First();

ProdCatID.CategoryId = null;
DataContext.SubmitChanges();

var DelCat = (from cat in DataContext.Categories
             where cat.Id == Convert.ToInt32(Id)
             select cat).ToList();

DataContext.Categories.DeleteAllOnSubmit(DelCat);
DataContext.SubmitChanges();

m trying to do is to check if there is any product with that CategoryId , if there is - I want to set the CategoryID to null and then delete the row from the类别表。

当我的产品有CategoryId但我无法删除时,它正常工作。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您只是将第一个具有此CategoryID的产品设置为null - 您需要处理具有该ID的所有产品!

var products = (from prod in DataContext.Products
                where prod.CategoryId == Convert.ToInt32(Id)
                select prod).ToList();

foreach(Product p in products)
{
    p.CategoryId = null;
}

DataContext.SubmitChanges();

.....

之后,现在您应该能够从表中删除该类别

答案 1 :(得分:0)

简单! 更改数据库中的Product表配置!

ALTER TABLE Product 
ADD CONSTRAINT 'Category_FK'
    FOREIGN KEY (CategoryId)
    REFERENCES Category(Id)
    ON DELETE SET NULL;

每当你删除一个主键时都会自动输入null!

答案 2 :(得分:0)

Cascade on Delete存在于实体框架中。当删除主记录时,级联删除会自动删除相关记录或将null设置为foreignkey属性。

这是父母和孩子之间的一对多关系

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}

有关详情,请查看:http://www.entityframeworktutorial.net/code-first/cascade-delete-in-code-first.aspx