2013-12-11 53 views
0

我在asp.netNet MVC項目中使用BaseRepository。編輯操作工作,但在添加操作,我應該伎倆,使其工作。具體而言,我的基地倉庫和BaseEntity類:BlToolkit在BaseRepository類中插入數據失敗

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; } 
    } 

我試過三種方式添加操作,使其工作。前兩種方式給出了錯誤。

第一種方式(不工作):

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

     return entity; 
    } 

錯誤消息: Cannot insert explicit value for identity column in table '...' when IDENTITY_INSERT is set to OFF.

-

方式二(不工作):

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

     return entity; 
    } 

錯誤消息: Operation is not valid due to the current state of the object.

-

第三條道路(工作):

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

     return entity; 
    } 

-

編輯操作而不會出現錯誤,但爲我需要的添加操作製作一些技巧。普通的Add操作有什麼問題,有沒有辦法讓它工作?

我試圖@MladenMacanović的建議和我添加Identity屬性在基BaseEntity類主鍵,然後所示誤差以上走了具有整型主鍵實體。如上圖所示

錯誤走了有主鍵的int類型的實體:

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

但是,這是不是一個完整的解決方案,因爲,我的一些實體有型的Guid的主鍵,因此向它們添加Identity屬性會產生另一個錯誤。

InsertBatch方法在不使用Identity屬性的情況下工作。因此,您可以在標識列的BaseEntity類中添加數據而不使用Identity屬性。 insertbatch方法有什麼區別?如何在不使用InsertBatch方法的情況下解決上述錯誤?

回答

1

問題出在你的數據庫表上。這就是爲什麼你會收到IDENTITY_INSERT錯誤。轉到SQL Server Management Studio,右鍵單擊表格Design,對於主鍵列,將屬性Identity Specification - >(Is identity)設置爲Yes。