【问题标题】:How to do this SQL in LINQ?如何在 LINQ 中执行此 SQL?
【发布时间】:2013-05-23 15:30:25
【问题描述】:

我想知道如何使用 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,然后我也可以插入其他表。

【问题讨论】:

    标签: asp.net linq sql-server-2008 linq-to-sql


    【解决方案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();
    

    【讨论】:

    • 所以这会将id从插入的产品传递到产品详细信息表等等?
    • 应该...假设 id 是自动生成的。
    • 谢谢,我试试看。
    【解决方案2】:

    首先,您需要一个 DataContext,它将您的数据库表示为 Linq 对象。

    请看这里: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 SQL101 LINQ Samples

    (也许它有点过时了,因为它是从 2007 年开始的,但你明白了)

    【讨论】:

    • 感谢您的回复,我已经知道一些 LINQ,但是上面是 SPROC 的一部分,它将数据保存到我的数据库中的不同表中。基本上我需要插入获取该 ID,然后我也可以插入到其他表中。
    • @thatuxguy 通常你可以执行多个SubmitChangesID 将出现在Product 实例上。如果使用 SPROC,则需要返回新生成的 id。也许这有帮助link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多