如何在LINQ中插入表上的表?

时间:2012-08-24 22:45:18

标签: c# .net linq

假设我与客户和产品之间存在1:1的关系。所以我要为两者添加一个表。在我的LINQ to SQL文件中,我使用键和.dbml中的关联进行了大量设置。

现在我插入两个应关联的表:

    CustomerDataContext dc = new CustomerDataContext();
    Table<Customer> customers = dc.GetTable<Customer>();
    Table<Product> products= dc.GetTable<Product>();

    Customer newCustomer = new Customer ();
    Product newProduct   = new Product();


    customers.InsertOnSubmit(newCustomer);
    products.InsertOnSubmit(newProduct);
    customers.Context.SubmitChanges();

那么如何在此时建立关联呢?因此,当我查询此Customer表时,我可以调用相关的Product,例如Customer.Product?

这甚至可能吗?

招呼

1 个答案:

答案 0 :(得分:0)

CustomerDataContext dc = new CustomerDataContext();
Table<Customer> customers = dc.GetTable<Customer>();
Table<Product> products= dc.GetTable<Product>();
Table<ProductConsumer> ProductConsumers= dc.GetTable<ProductConsumer>();

Customer newCustomer = new Customer ();
Product newProduct   = new Product();


customers.InsertOnSubmit(newCustomer);
products.InsertOnSubmit(newProduct);
customers.Context.SubmitChanges();
products.Context.SubmitChanges();

//Now insert associations
ProductConsumer= new ProductConsumer();
ProductConsumer.Consumer= newCustomer ;
ProductConsumer.Product= newProduct  ;


ProductConsumers.InsertOnSubmit(ProductConsumer)
ProductConsumers.Context.SubmitChanges();