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 ?
I got the answer when I make a demo for my question, I solved it by comment the line in Tags.cs:
public TagUseCount TagUseCount { get; set; }
But I don't know why?
Here is my TagUseCount.cs below:
public class TagUseCount
{
public int TagId { get; set; }
public int UseCount { get; set; }
public Tags Tag { get; set; }
public enum Operation
{
None = 0,
Increment = 2,
Decrement = 4
}
}
Supply: I research it and I found the error come from the code that I write in modelBuilder:
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);
When I change the code like that: it helps.
modelBuilder.Entity<Tags>().ToTable("Tags")
.HasKey(x => x.TagId);
modelBuilder.Entity<Tags>()
.HasOne(x => x.TagUseCount)
.WithOne(y => y.Tags)
.HasForeignKey(z => z.TagId)
modelBuilder.Entity<TagUseCount>().ToTable("TagUseCount")
.HasKey(x => x.TagId);