EF Core給我錯誤當IDENTITY_INSERT設置為OFF時,無法在表'標籤'中為標識列插入顯式值

asp.net-core c# 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);

我瘋了幾天,誰能幫幫我?

一般承認的答案

當我為我的問題做一個演示時,我得到了答案,我通過在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);


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow