ironcurtain
ironcurtain

Reputation: 690

Entity Framework BulkInsert

I have created BulkInsert method as below:

public void BulkInsertUsers(IEnumerable<tblUsers> users)
{
    using (var ctx = new Entities())
    {
        ctx.BulkInsert(users);
        ctx.SaveChanges();
    }
}

Mu problem is that ctx.BulkInsert(users); returns error:

Type 'Infrastructure.EF.tblUser' is not found in context 'Infrastructure.EF.Entities'

In debug mode, when I expanded ctx variable, I've found that some entities have value like:

System.Data.Entity.DbSet<Automation.Infrastructure.EF.EntityName>

and some other have:

SELECT 
    [Extent1].[ID] AS [ID], 
    [Extent1].[Name] AS [Name], 
FROM [dbo].[tbl] AS [Extent1]

For those entities which have SELECT value, BulkInsert works fine. I am using

EntityFramework.BulkInsert, Version=6.0.2.8

Upvotes: 0

Views: 131

Answers (1)

IronAces
IronAces

Reputation: 1883

You are attempting to add the entity Users within an Entities context. See below

public void BulkInsertUsers(IEnumerable<tblUsers> users)
{
    using (var ctx = new tblUsers())
    {
        // users is detached from database, so we need to add it
        ctx.Attach(users); 
        // Specify that these are modified entities (may not be necessary for BulkInsert)
        // I don't know what properties users contain, so used Name
        ctx.Entry(tblUsers).Property(a => a.Name).IsModified = true;
        ctx.BulkInsert(users);
        ctx.SaveChanges();
    }
}

Something to think about... You could make a generic method to BulkInsert different entities. This may help you out: A generic way to save an entity in Entity Framework

Upvotes: 2

Related Questions