Speed up LINQ inserts

前端 未结 11 1631
自闭症患者
自闭症患者 2021-02-01 07:46

I have a CSV file and I have to insert it into a SQL Server database. Is there a way to speed up the LINQ inserts?

I\'ve created a simple Repository method to save a rec

11条回答
  •  时光取名叫无心
    2021-02-01 08:05

    Converting this to a compiled query is the easiest way I can think of to boost your performance here:

    Change the following:

        Offer dbOffer = this.db.Offers.SingleOrDefault (
             o => o.offer_id == offer.offer_id);
    

    to:

    Offer dbOffer = RetrieveOffer(offer.offer_id);
    
    private static readonly Func RetrieveOffer
    {
       CompiledQuery.Compile((DataContext context, int offerId) => context.Offers.SingleOrDefault(o => o.offer_id == offerid))
    }
    

    This change alone will not make it as fast as your ado.net version, but it will be a significant improvement because without the compiled query you are dynamically building the expression tree every time you run this method.

    As one poster already mentioned, you must refactor your code so that submit changes is called only once if you want optimal performance.

提交回复
热议问题