BlToolkit insert data failure in BaseRepository class

596 views Asked by At

I'm using BaseRepository in asp .Net MVC project. Edit operation works but in Add operation, I should make a trick to make it work. In detail, my base repository and BaseEntity classes:

public class BaseRepository<TEntity, T> : IRepository<TEntity, T> where TEntity : BaseEntity<T>
{
    private DbManager _context;

    private Table<TEntity> Table
    {
        get { return _context.GetTable<TEntity>(); }
    }

    public BaseRepository(DbManager context)
    {
        _context = context;
    }

    //...

    public TEntity Add(TEntity entity)
    {
        //...

        return entity;
    }

    public TEntity Edit(TEntity entity)
    {
        _context.Update(entity);

        return entity;
    }

    //...
}

public class BaseEntity<T>
    {
        [PrimaryKey]
        public T Id { get; set; }
    }

I tried three ways for Add operation to make it work. First two ways gave errors.

First way(Doesn't work):

public TEntity Add(TEntity entity)
    {
        _context.Insert(entity);            

        return entity;
    }

Error Message: Cannot insert explicit value for identity column in table '...' when IDENTITY_INSERT is set to OFF.

--

Second way(Doesn't work):

public TEntity Add(TEntity entity)
    {
        Table.Insert(() => entity);          

        return entity;
    }

Error Message: Operation is not valid due to the current state of the object.

--

Third way(Working):

public TEntity Add(TEntity entity)
    {
        var l = new List<TEntity> { entity };
        _context.InsertBatch(l);            

        return entity;
    }

--

Edit operation works without error, but for Add operation I need to make some trick. What is the problem with normal Add operation and, is there a way to make it work?

I tried advice of @Mladen Macanović and I added Identity attribute to primary key in base BaseEntity class, then errors shown above gone for entities having int type primary key.

Errors shown above gone for entities having int type of primary key:

public class BaseEntity<T>
    {
        [PrimaryKey Identity]
        public T Id { get; set; }
    }

But, this is not a full solution because, some of my entities have primary key in type of Guid, so adding Identity attribute to them gives another error.

InsertBatch method works without using Identity attribute. So, you can add data without using Identity attribute in BaseEntity class for Identity column. What is the difference of insertbatch method? How can I resolve errors shown above without using InsertBatch method?

1

There are 1 answers

0
Mladen Macanović On

The problem is with your database table. That is why you're getting the IDENTITY_INSERT error. Go to the SQL Server Management Studio, right click on the table, Design, and for the primary key column set the property Identity Specification -> (Is identity) to Yes.