bulk insert and update with ADO.NET Entity Framework

て烟熏妆下的殇ゞ 提交于 2020-01-14 03:00:07

问题


I am writing a small application that does a lot of feed processing. I want to use LINQ EF for this as speed is not an issue, it is a single user app and, in the end, will only be used once a month.

My questions revolves around the best way to do bulk inserts using LINQ EF.

After parsing the incoming data stream I end up with a List of values. Since the end user may end up trying to import some duplicate data I would like to "clean" the data during insert rather than reading all the records, doing a for loop, rejecting records, then finally importing the remainder.

This is what I am currently doing:

DateTime minDate = dataTransferObject.Min(c => c.DoorOpen);
DateTime maxDate = dataTransferObject.Max(c => c.DoorOpen);

using (LabUseEntities myEntities = new LabUseEntities())
{
    var recCheck = myEntities.ImportDoorAccess.Where(a => a.DoorOpen >= minDate && a.DoorOpen <= maxDate).ToList();
    if (recCheck.Count > 0)
    {
        foreach (ImportDoorAccess ida in recCheck)
        {
            DoorAudit da = dataTransferObject.Where(a => a.DoorOpen == ida.DoorOpen && a.CardNumber == ida.CardNumber).First();
            if (da != null)
                da.DoInsert = false;
        }
    }

    ImportDoorAccess newIDA;
    foreach (DoorAudit newDoorAudit in dataTransferObject)
    {
        if (newDoorAudit.DoInsert)
        {
            newIDA = new ImportDoorAccess
            {
                CardNumber = newDoorAudit.CardNumber,
                Door = newDoorAudit.Door,
                DoorOpen = newDoorAudit.DoorOpen,
                Imported = newDoorAudit.Imported,
                RawData = newDoorAudit.RawData,
                UserName = newDoorAudit.UserName
            };
            myEntities.AddToImportDoorAccess(newIDA);
        }
    }
    myEntities.SaveChanges();
}

I am also getting this error:

System.Data.UpdateException was unhandled
Message="Unable to update the EntitySet 'ImportDoorAccess' because it has a DefiningQuery and no element exists in the element to support the current operation."
Source="System.Data.SqlServerCe.Entity"

What am I doing wrong?

Any pointers are welcome.


回答1:


You can do multiple inserts this way.

I've seen the exception you're getting in cases where the model (EDMX) is not set up correctly. You either don't have a primary key (EntityKey in EF terms) on that table, or the designer has tried to guess what the EntityKey should be. In the latter case, you'll see two or more properties in the EDM Designer with keys next to them.

Make sure the ImportDoorAccess table has a single primary key and refresh the model.



来源:https://stackoverflow.com/questions/2587542/bulk-insert-and-update-with-ado-net-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!