これは私のエンティティ:
public class Audit
{
public string Pk { get; set; }
public string TableName { get; set; }
public string RowPk { get; set; }
public string ActionType { get; set; }
public string RowContent { get; set; }
}
これは私のマッピングです:
modelBuilder.Entity<Audit>(entity =>
{
entity.HasKey(e => e.Pk).IsClustered(true);
entity.Property(e => e.Pk)
.ValueGeneratedOnAdd()
.UseIdentityColumn()
.HasConversion(new ValueConverter<string, long>(v => Convert.ToInt64(v),v => Convert.ToString(v)));
entity.Property(e => e.TableName).IsRequired().HasMaxLength(255);
entity.Property(e => e.RowPk).IsRequired().HasMaxLength(100);
entity.Property(e => e.ActionType).IsRequired().HasMaxLength(1);
entity.Property(e => e.RowContent).IsRequired;
});
私の要件:
Audit.Pk: string
Pk列: BigInt
およびAutoIncrement
移行を追加すると、次のエラーが発生します。
プロパティタイプが「文字列」であるため、エンティティタイプ「監査」のプロパティ「Pk」にID値生成を使用できません。 ID値の生成は、符号付き整数プロパティでのみ使用できます。
回避策はありますか?
個人的には、 string
はprimary key
一般的なデータ型ではありません。ほとんどの場合、 int
またはGUID
を使用しGUID
。あなたの問題を解決するには、以下のスニペットを使用できます:
public class Audit
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; } //instead of Pk
[NotMapped]
public string Pk => Id.ToString();
.
.
.
}
そして最後に、マッピングからPk
プロパティに関連するすべてのコードを削除します
bigint主キーを保持すると、SQLテーブルのメンテナンスが容易になります。それ以外の場合は、主キーのPK
をGUIDなどに変更します。
それ以外の場合は、クラスへの次の変更により、プログラムでPkStringが必須になることをお勧めします(この変更はデータベースに対して透過的です)。
public class Audit
{
[Key]
public long Pk { get; set; }
[NotMapped]
public string PkString => Pk.ToString();
public string TableName { get; set; }
public string RowPk { get; set; }
public string ActionType { get; set; }
public string RowContent { get; set; }
}