我想知道如何使用LINQ(C#)执行以下操作。非常感谢所有的帮助,谢谢。
DECLARE @productId int
INSERT INTO product(title, studioId, developerId, publisherId, releasedateUK, releasedateUS, certUK, certUS, dateAdded, pageSlug)
VALUES (@title, @studioId, @developerId, @publisherId, CONVERT(Date, @releaseDateUK, 103), CONVERT(Date, @releaseDateUS, 103), @certUK, @certUS, GETDATE(), @Slug)
SET @productId = SCOPE_IDENTITY()
--Insert Product Details
INSERT INTO productDetails(productId, is3D, is4K, isTriplePlay, hasDVD, hasDigital, running, regiona, regionb, regionc, releaseYear, synopsis, imdbrating)
VALUES (@productId, @is3D, @is4K, @isTriplePlay, @hasDVD, @hasDigital, @runningTime, @regiona, @regionb, @regionc, @releaseYear, @synopsis, @imdbrating)
更新:这是来自我写的SPROC,我基本上需要插入一个产品,获取该ID,以便我可以插入其他表格。
答案 0 :(得分:1)
首先,您需要一个DataContext,它将您的数据库表示为Linq Objects。
见这里:How to: Add LINQ to SQL Classes to a Project
或者在这里:Walkthrough: Creating LINQ to SQL Classes
在DataContext中,您将找到数据库中每个表的实体。 当您现在想要在数据库中创建新行时,首先需要创建一个新行 来自您实体的实例。
Product newProduct = new Product( );
newProduct.Title = "Your own title";
newProduct.StudioId = 1234;
[...]
当您准备好使用数据填充实体时,可以在dataContext中传递它。
YourDataContext.Products.InsertOnSubmit( newProduct );
最后你提交了你的更改:
YourDataContext.SubmitChanges( );
我建议您阅读一下:Using Linq to SQL和101 LINQ Samples
(也许它有点过时,因为它来自2007年,但你明白了)
答案 1 :(得分:1)
我会做这样的事情......假设Product和ProductDetails是一对多的。
如果是一比一,那么您可以设置product.ProductDetail = new ProductDetail {};
var ctx = new DataBaseContext();
var product = new Product{
Title = "Title",
etc..
etc...
};
product.ProductDetails.Add(new ProductDetail{
is4K = true,
etc..
etc..
});
ctx.Products.InsertOnSubmit(product);
ctx.SubmitChanges();