LinQ的级联操作
现在我开始做一个linq的级联操作,给大家参考:
1.我首先新建了两张表一个是category,一个是product.
category表
product表:
2.然后添加关联:
ALTER TABLE product ADD CONSTRAINT [FK_ product _Key] FOREIGN KEY
(
catid
)REFERENCES Category
(
catid
)
GO
3.代码:
添加的级联代码是:
Category_Product_ContextDataContext cpcontext
=
new
Category_Product_ContextDataContext(System.Configuration.ConfigurationManager.ConnectionStrings[
"
TestConnectionString
"
].ToString());
//
级联添加
Category cat
=
new
Category()
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
Catid =1005,
CatName = "设计",
CatDescription = "好多设计 "
}
;
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
Product p1
=
new
Product()
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
ProductName = "平面设计",
ProductDescripton = "设计大",
Category=cat
}
;
Product p2
=
new
Product()
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
ProductName = "立体设计",
ProductDescripton = "新电脑",
Category = cat
}
;
Product p3
=
new
Product()
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
ProductName = " 室内设计",
ProductDescripton = " 室内设计林",
Category = cat
}
;
Product p4
=
new
Product()
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
ProductName = "产品设计",
ProductDescripton = "林",
Category = cat
}
;
Product p5
=
new
Product()
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
ProductName = "建筑设计",
ProductDescripton = "在",
Category = cat
}
;
cpcontext.Categories.InsertOnSubmit(cat);
cpcontext.SubmitChanges();
删除的级联代码:
删除的原则是:先删除从表的再删除主表的
Category_Product_ContextDataContext cpcontext
=
new
Category_Product_ContextDataContext(System.Configuration.ConfigurationManager.ConnectionStrings[
"
TestConnectionString
"
].ToString());
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
Category singlecats
=
cpcontext.Categories.Single(p
=>
p.Catid
==
1004
);
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
foreach
(Product p
in
cpcontext.Products.Where(p
=>
p.CatId
==
1004
))//删除从表
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
cpcontext.Products.DeleteOnSubmit(p);
}
cpcontext.Categories.DeleteOnSubmit(singlecats);//删除主表
cpcontext.SubmitChanges();