LinQ的级联操作

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()
       
{
           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();

 

删除的级联代码:

删除的原则是:先删除从表的再删除主表的

 

 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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田猿笔记

写文章不容易,希望大家小小打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值