My project using DDD pattern,is built by .NET-core and EF core. Today, I meet a question is that when I add a tag entity to my database, then do saveChanges. But the program throw a Exception: "Cannot insert explicit value for identity column in table 'Tags' when IDENTITY_INSERT is set to OFF"
And I am puzzled, also, I search the question on the stackoverfolw and google. I found some solution is that use the attribute
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
, but is doesn't work for me. Here is my code below:
C#//Entity
public class Tags
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int TagId { get; set; }
public string TagName { get; set; }
public TagUseCount TagUseCount { get; set; }
public enum Operation
{
None = 0,
Add = 2,
Update = 4
}
}
The Function use in my Service Lawyer:
var tagEntity = new Tags { TagName = tag };
var tagId = await _tagRepository.Add(tagEntity);
The Add Function is Repository Lawyer:
public async Task<int> Add(Tags tags)
{
try
{
_unitOfWork.Add(tags);
await _unitOfWork.CommitAsync();
return tags.TagId;
}
catch (Exception ex)
{
_logger.LogError(new EventId(), ex, "Error when add Tag!");
}
return 0;
}
UOW Add Method:
TEntity IUnitOfWork.Add<TEntity>(TEntity entity)
{
return base.Set<TEntity>().Add(entity).Entity;
}
Version of EF core :"Microsoft.EntityFrameworkCore": "1.1.0"
ModelBuilder below:
modelBuilder.Entity<Tags>().ToTable("Tags")
.HasKey(x => x.TagId);
modelBuilder.Entity<TagUseCount>().ToTable("TagUseCount")
.HasKey(x => x.TagId);
modelBuilder.Entity<TagUseCount>().ToTable("TagUseCount")
.HasOne(x => x.tags)
.WithOne(q => q.tagUseCount);
I am crazy with it for a couple of days, Who can help me ?
TagId
somewhere in the code? Can we see the UOWAdd
method as well? Also what version of EF Core are you using? We probably can help, but need minimal reproducible example, i.e. something we can copy/paste and run.public TagUseCount TagUseCount { get; set; }
, but I don't know why?