EF Core给我错误无法在表格中插入标识列的显式值'标签'当IDENTITY_INSERT设置为OFF时

时间:2017-03-04 10:05:16

标签: c# asp.net-core entity-framework-core

我的项目使用DDD模式,由.NET-core和EF核心构建。今天,我遇到的一个问题是,当我向我的数据库添加标签实体时,请执行saveChanges。但该程序抛出异常:"无法在表格中插入标识列的显式值'标记'当IDENTITY_INSERT设置为OFF" 我很困惑,我也在stackoverfolw和google上搜索问题。我发现一些解决方案是使用该属性 [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)],但对我不起作用。以下是我的代码:

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

我的服务律师中的功能使用:

var tagEntity = new Tags { TagName = tag };
var tagId = await _tagRepository.Add(tagEntity);

添加功能是存储库律师:

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添加方法:

TEntity IUnitOfWork.Add<TEntity>(TEntity entity)
    {
        return base.Set<TEntity>().Add(entity).Entity;     
    }

Version of EF core :"Microsoft.EntityFrameworkCore": "1.1.0"

下面的模型构建器:

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

我疯了几天,谁能帮帮我?

1 个答案:

答案 0 :(得分:2)

当我为我的问题做一个演示时,我得到了答案,我通过评论Tags.cs中的行来解决它:

public TagUseCount TagUseCount { get; set; }

但我不知道为什么?

以下是我的TagUseCount.cs:

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

供应: 我研究它,我发现错误来自我在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);

当我改变代码时:它会有所帮助。

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