本文讲解了linq级联操作,从添加,删除linq级联等方面都做了介绍。
现在我开始做一个linq级联操作,给大家参考:
1.我首先新建了两张表一个是category,一个是product.
category表
product表
2.然后添加linq级联:
- ALTER TABLE product ADD CONSTRAINT [FK_ product _Key] FOREIGN KEY
- (
- catid
- )REFERENCES Category
- (
- catid
- )
- GO
3.代码:添加的linq级联代码是:
- Category_Product_ContextDataContext cpcontext =
- new Category_Product_ContextDataContext
- (System.Configuration.ConfigurationManager.ConnectionStrings
- ["TestConnectionString"].ToString());
- // 级联添加
- Category cat=new Category()
- ...{
- Catid =1005,
- CatName = "设计",
- CatDescription = "好多设计 "
- };
- Product p1 = new Product()
- ...{
- ProductName = "平面设计",
- ProductDescripton = "设计大",
- Category=cat
- };
- Product p2 = new Product()
- ...{
- ProductName = "立体设计",
- ProductDescripton = "新电脑",
- Category = cat
- };
- Product p3 = new Product()
- ...{
- ProductName = " 室内设计",
- ProductDescripton = " 室内设计林",
- Category = cat
- };
- Product p4 = new Product()
- ...{
- ProductName = "产品设计",
- ProductDescripton = "林",
- Category = cat
- };
- Product p5 = new Product()
- ...{
- ProductName = "建筑设计",
- ProductDescripton = "在",
- Category = cat
- };
- cpcontext.Categories.InsertOnSubmit(cat);
- cpcontext.SubmitChanges();
删除的linq级联代码:
删除的原则是:先删除从表的再删除主表的
- Category_Product_ContextDataContext cpcontext =
- new Category_Product_ContextDataContext
- (System.Configuration.ConfigurationManager.ConnectionStrings
- ["TestConnectionString"].ToString());
- Category singlecats = cpcontext.Categories.Single
- (p => p.Catid == 1004);
- foreach (Product p in cpcontext.Products.Where(p => p.CatId == 1004))
- //删除从表
- ...{
- cpcontext.Products.DeleteOnSubmit(p);
- }
- cpcontext.Categories.DeleteOnSubmit(singlecats);//删除主表
- cpcontext.SubmitChanges();
以上就是对linq级联操作的简单介绍。
【编辑推荐】