如何加快sql创建过程

时间:2017-09-26 06:41:09

标签: c# sql entity-framework

在我的应用程序中,我创建行到sql表。

int findNewId = Entities.myTable.Where(a => a.Name == txtName.Text).Select(b => b.Id).FirstOrDefault();

for (int i = 0; i < incomingDtbl.Rows.Count; i++)
{
    addNew.Id = findNewId;
    addNew.Date = Convert.ToDateTime(incomingDtbl.Rows[i].ItemArray[2]);
    addNew.Hour = Convert.ToInt32(incomingDtbl.Rows[i].ItemArray[3]);
    ...
    addNew.CreationDate = System.DateTime.Now;
    Entities.myTable.Add(addNew);
    Entities.SaveChanges();

}

但我的incomingDtbl有130000行,所以需要太长时间。 有没有办法加快这个过程?

我无法直接批量复制incomingDtbl,因为它没有newId。

1 个答案:

答案 0 :(得分:0)

我也遇到了类似的问题(我的是170,000行)。这是我的解决方案:

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Enumeration"%>
<%@page import="java.util.Vector"%>
<%@page import="java.util.TreeSet"%>
<%@page import="java.util.Iterator"%>

<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="com.BTParameterStrategyMaintenanceDetails"%>
<%@page import="javax.servlet.http.HttpSession" %>

<script>
    function getCListt(val) {
        alert(val);
    }
</script>



<script>
 function OpenClose(obj) {
   HeadObj = eval(obj + "_Head");
   BodyObj = eval(obj + "_Body");

   if (BodyObj.style.display=='block') {
     BodyObj.style.display='none';
     SignOffset = HeadObj.innerHTML.indexOf("-");
     HeadObj.innerHTML = "+" + HeadObj.innerHTML.substring(SignOffset+1);
   } else {
     BodyObj.style.display='block';
     SignOffset = HeadObj.innerHTML.indexOf("+");
     HeadObj.innerHTML = "-" + HeadObj.innerHTML.substring(SignOffset+1);
   }
 }
</script>

 <script type="text/javascript">
    function GetSelectedTextValue(ddlFruits) {
        var selectedText = ddlFruits.options[ddlFruits.selectedIndex].innerHTML;
        var selectedValue = ddlFruits.value;

        alert("Selected Text: " + selectedText + " Value: " + selectedValue);
    }
</script>








<%
    HttpSession session1 = request.getSession();
    ArrayList sampleStrategyRecords = (ArrayList) session1.getAttribute("allRiskCat");
    System.out.println("number of records to be displayed : " + sampleStrategyRecords.size()); 

    %>
    <form action="/getChanges" >

    <%for(int i=0;i<sampleStrategyRecords.size();i++){
    String id = "ClickMe"+i+"_Head";
    String id1 = "ClickMe"+i+"_Body";
    String onClick = "ClickMe"+i ;
    %>

    <div  id="<%= id %>" onClick="OpenClose('<%= onClick %>')" onMouseOver="this.style.cursor='pointer';" style="color: #000099;">
    <button>
    Risk Category <%= i %> 
    </button>
    </div>


        <%ArrayList ListIterator = (ArrayList) sampleStrategyRecords.get(i);
        System.out.println("ListIteartor :: "+ListIterator.size());
        System.out.println("**********");%>
        <div id="<%= id1 %>" style="display:none; margin-left:20px"><table>

<tr>
<th>Risk Category</th>
<th>Channel Description</th>
<th>Bureau Level Description</th>
<th>Champion Strategy</th>
<th>Challenger Strategy</th>
<th>S2PC</th>
</tr>
        <%
        for(int j=0;j<ListIterator.size();j++){

            BTParameterStrategyMaintenanceDetails bean = (BTParameterStrategyMaintenanceDetails)ListIterator.get(j);

            ArrayList updatedList = new ArrayList();%>

            <tr>
            <td align = "left"><%= bean.getRiskCategory() %></td>
            <td align = "left"><%= bean.getChannelDescription() %></td>
            <td align = "left"><%= bean.getBureauLevelDescription() %></td>
            <td align = "left"><select name="champDesc" id="champDesc" onchange=updatedList.add(bean) >

            <%System.out.println("updated list size :: "+ updatedList.size()); %>

                <%if (bean.getChampStrategyDesc() != null) {
                    for(int s=1;s<10;s++){

                    if(bean.getChampStrategyValue().equals(Integer.toString(s))){

                    %> 

                    <option value="<%=bean.getChampStrategyValue()%>"  selected="selected" > Champion Strategy <%=bean.getChampStrategyValue()%> </option>
                <%}else{

                    %>
                    <option value="<%= s %>">Champion Strategy <%=s %></option>
                <%} 
                }
                }%>



            </select></td>
            <td align = "left"><select name="clngrDesc" id="clngrDesc">
            <%if (bean.getChallengerDesc()!= null) {
                    for(int s=1;s<10;s++){

                    if(bean.getChallengerValue().equals(Integer.toString(s))){%> 
                    <option value="<%=bean.getChallengerValue() %>" selected="selected"> Challenger Strategy <%=bean.getChallengerValue() %> </option>
                <%}else{

                    %>
                    <option value="<%= s %>">Challenger Strategy <%=s %></option>
                <%}
                }
                }
                 %>
                 </select>
                 </td>
            <td align = "left">
            <select name="s2pc" id="s2pc">
            <%if (bean.getS2pc()!= null) {
                    for(int s=0;s<101;s++){

                    if(bean.getS2pc().equals(Integer.toString(s))){%> 
                    <option value="<%=bean.getS2pc() %>" selected="selected"> <%=bean.getS2pc() %> </option>
                <%}else{

                    %>
                    <option value="<%= s %>"><%=s %></option>
                <%}
                }
                }
                 %>
                 </select>
            </td>

            </tr>


        <%} %>
        </table></div>
 <% }
    session1.setAttribute("checkList",sampleStrategyRecords);
    ArrayList checkList = (ArrayList) session.getAttribute("checkList");
    System.out.println("checkList size :: "+checkList.size());
%>

<input class="DataEntryButton" name="submit_button" type="submit" value="Submit" />



</form>
    public bool InsertData(List<MachineInfo> MachineInfo, string flag,int userID)
    {
        if (MachineInfo != null && flag != string.Empty)
        {
            List<T> attList = new List<T>();
            foreach (var item in MachineInfo)
            {
                T att = new T()
                {
                    CreatedDate = DateTime.Now,
                    DateTime = item.DateTimeRecord,
                    EnrollNumber = item.EnrollNumber.ToString(),
                    IPFlag = flag,
                    SyncBy = userID
                };
                attList.Add(att);
            }
            try
            {
                Entities context = null;
                try
                {
                    context = new Entities();
                    context.Configuration.AutoDetectChangesEnabled = false;

                    int count = 0;
                    foreach (var entity in attList)
                    {
                        ++count;
                        context = AddToContext(context, entity, count, 100, true);
                    }

                    context.SaveChanges();
                }
                finally
                {
                    if (context != null)
                        context.Dispose();
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        return false;
    }

它执行速度非常快,因为它会拆分记录并帮助您验证。

一切顺利!!!