Alexey Zorchenkov
Alexey Zorchenkov

Reputation: 83

Entity framework exclude fields from insert

I have Model class:

public class position
{
    public string positioncode { get; set; }
    public string english { get; set; }
    public string chinese { get; set; }
    public string big5 { get; set; }
    public string jd { get; set; }
    public string japanese { get; set; }
    public int orgid { get; set; }
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int positionid { get; set; }
}

DBContext:

public System.Data.Entity.DbSet<TestWebAPI1.Models.position> positions { get; set; }

and controller post method, where I have to insert record into database based on incoming JSON html:

    // POST api/position
    [ResponseType(typeof(position))]
    public async Task<IHttpActionResult> Postposition(position theposition)
    {
        db.positions.Add(theposition);
        await db.SaveChangesAsync();
    }

My question is: whether is it possible to generate insert statement based on the fields, received in JSON and avoid NULLS in the fields, which were omitted in JSON, like:

insert into position (positionid, positioncode ) values (2, "TEMP");

instead of insert statement with all fields listed, which is by default entity framework behavior.

Upvotes: 2

Views: 4372

Answers (1)

Alex Voskresenskiy
Alex Voskresenskiy

Reputation: 2233

Here is a rather straight-forward solution you can use.

Define a different context like this:

public class PositionsContext:DbContext
{
    public DbSet<Position> Type { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        //define ignores here
        modelBuilder.Entity<Position>().Ignore(t => t.big5);
    }
}

And define ignores as you need em. But first, read my answer to bottom, i think you walk in wrong direction trying to achieve performance here. Your overhead on using EF will totally ruin all your optimization with nulls in insert statements.I performed a simple test:created a table with 40 columns and made 2 inserts:one was with huge amount of nulls(for 38 columns) and another was 'insert into #Test(Id) Values(1)'.Yep,the second worked a little faster(i inserted 100000 rows, first took 2 secs,second- 1.5 sec).But EF definitely cannot insert even 1000 rows per second. If you need performance, you need to deal with EF batching, transactions and so on, but not with inserts statement size

Upvotes: 1

Related Questions